javascript 如何在javascript中动态地将项目添加到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10632180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:31:17  来源:igfitidea点击:

how to add items to an array dynamically in javascript

javascriptjqueryhighcharts

提问by nashr rafeeg

First of all I am a total javascript newbie so please bear with me. I have the following script to draw pie charts using the Highchart framework

首先,我是一个 javascript 新手,所以请多多包涵。我有以下脚本使用 Highchart 框架绘制饼图

$(function() {
    var options = {
        colors: ["#66CC00", "#FF0000", "#FF6600"],
        chart: {
            renderTo: 'container',
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: true
        },
        title: {
            text: 'Host Status'
        },
        tooltip: {
            formatter: function() {
                return '<b>' + this.point.name + '</b>: ' + this.total;
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    formatter: function() {
                        return '<b>' + this.point.name + '</b>';
                    }
                }
            }
        },
        series: [{
            type: 'pie',
            name: 'service status',
            data: []
        }]
    }

    var chart;
    options.series.data.push('['
    Service Ok ',   45.0]')
    $(document).ready(function() {
        chart = new Highcharts.Chart(options)
    });

});?

What i am trying to do is to dynamically load the values into series.dataarray as an array of objects. What am doing wrong here, and is there a better way to load the data into the data array?

我想要做的是将值series.data作为对象数组动态加载到数组中。这里做错了什么,有没有更好的方法将数据加载到数据数组中?

回答by McGarnagle

The seriesproperty is an array, so you would need to write it like this (to add a single data point to the series):

系列属性是一个数组,所以你需要把它写这样的(增加一个数据点系列):

options.series[0].data.push( ["Service Ok", 45.0 ]);

I was looking at this JS Fiddle.

我在看这个 JS Fiddle

回答by Ricardo Alvaro Lohmann

You have an error on your code:
You said you want to dynamically load the values, rigth ?
But you code just sets the initial serie data and then render it.
So in your case if you want to 'dinamically' change your serie data you have to destroy the current chart, update it's data and then render it again. Propably you loss performance.

The correct way to do itis using highstock api and don't update it manually. If you do it probably you'll get some errors when you use chart zoom, because to update the chart points this api have to calculate the points again, and it's made when you use the functions above.
As you can see on the serie referenceto update your chart data you have to use the following functions:
Set new data: chart.series[0].setData(newData, redraw);example
Add a new point: chart.series[0].addPoint(arrayOfPoints, redraw);example

您的代码有错误:
您说要动态加载值,rigth 吗?
但是您的代码只是设置初始系列数据然后渲染它。
因此,在您的情况下,如果您想“动态”更改您的系列数据,您必须销毁当前图表,更新它的数据,然后再次渲染它。可能你会损失性能

做正确的方法是使用highstock API和没有手动更新。如果你这样做了,你可能会在使用图表缩放时遇到一些错误,因为为了更新图表点,这个 api 必须再次计算点,这是在你使用上面的函数时产生的。
正如您在系列参考中看到的那样要更新您的图表数据,您必须使用以下功能:
设置新数据:chart.series[0].setData(newData, redraw);示例
添加新点:chart.series[0].addPoint(arrayOfPoints, redraw);示例

Look this fiddle, here I update the chart serie manually, without use api functions, and what happens ? Nothing.

看看这个小提琴,在这里我手动更新图表系列,不使用 api 函数,会发生什么?没有什么。

For the best performance you can use the following code:

为了获得最佳性能,您可以使用以下代码:

    function createChart() {
        chart = new Highcharts.Chart(options);
    }

    // when you want to update it's data
    $(element).yourEvent(function() {
        var newData = ['Service Ok', 50.0];
        if(chart.hasRendered) {
            chart.series[0].setData(newData, true);
        } else {
            // only use it if your chart isn't rendered
            options.series[0].data.push(newData);
            createChart();
        }
    });

$(function() {
    var options = {
        colors: ["#66CC00", "#FF0000", "#FF6600"],
        chart: {
            renderTo: 'container',
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: true
        },
        title: {
            text: 'Host Status'
        },
        tooltip: {
            formatter: function() {
                return '<b>' + this.point.name + '</b>: ' + this.total;
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    formatter: function() {
                        return '<b>' + this.point.name + '</b>';
                    }
                }
            }
        },
        series: [{
            type: 'pie',
            name: 'service status',
            data: ['Service Ok ',   45.0]
        }]
    }

    var chart;
    $(document).ready(function() {
        createChart();
    });
});?

回答by Eugene Trofimenko

I think it might helps you JavaScript push() Method specification

我认为它可能会帮助你 JavaScript push() 方法规范

and Highcharts control specification

Highcharts 控制规范

Seriesis an array of objects so you should do like this:

Series是一个对象数组,所以你应该这样做:

options.series[0].data.push(["Service Ok", 45.0 ])

In this case you will get

在这种情况下,你会得到

series: [{

    type: 'pie',

    name: 'service status',

    data: [
             ["Service Ok", 45.0 ]
          ]

    }]

DEMO with pie chart

带饼图的演示

回答by Paras

Try this

试试这个

$(function() {
var options = {   
    series: [{
        type: 'pie',
        name: 'service status',
        data: []
        }]
};    
    var objData={ "type":'bar','name':'second','data':[]};
    options.series.push(objData);
});?

回答by Kanishka Panamaldeniya

try

尝试

options.series[0]data[0]= 'Service Ok';
options.series[0]data[1]= 45.0;