简介
我正在从 DataTable 表创建 HighCharts 图。
我所做的是遍历表的行和列,将字符串(我们使用与美国不同的千位分隔符)转换为数字并将它们保存到名为 item
的对象中。该对象有两个值 item["name"]
是系列的名称,item["data"]
是系列的数据。然后,我使用 .push
方法将这些对象添加到一个数组中,以发送到 Highcharts options
对象来创建绘图。在下面的例子中,我只有三个系列,但问题总是出现。 LineOptions
是 HighCharts Graph 的选项对象。
代码
function plotLineOrBar(type){
var jsonData = [];
var xaxis = $('#masters_table table').find('thead th:not(:first-child)').map(function(){
return $(this).html();
}).get();
$('#masters_table table tbody tr').each(function(){
item = {};
item["name"] = $(this).find('td:first-child').html();
item["data"] = $(this).find('td:not(:first-child)').map(function(){
return parseInt($(this).html().replace(/\./g, "").replace('',0),10);
}).get();
jsonData.push(item);
});
console.log(jsonData[0]["name"]); // send the 0th name to console
console.log(jsonData[1]["name"]); // send the 1st name to console
console.log(jsonData[2]["name"]); // send the 2nd name to console
LineOptions.series = (jsonData);
LineOptions.xAxis.categories = xaxis;
LineOptions.chart.type=type;
var chart = new Highcharts.Chart(LineOptions);
}
问题 (系列名称应该是2320,2321,2336)
在 Chrome 中,生成的 console.log 是:
2320
2321
2336
并且每个系列的相应数据都正确打印出来,一切都完美无缺。
在 IE9 中,生成的 console.log 是:
LOG: 2336
LOG: 2336
LOG: 2336
即,只有最后一个系列被打印到数组中。结果是三个曲线完美重叠的系列,因为它们具有相同的数据。
我已经搜索并搜索了答案,绞尽脑汁,但我仍然无法弄清楚我做错了什么。不过,我假设我的错误很简单(我希望如此)。
最佳答案
正如之前在评论中所写(供将来引用),只需在循环函数中定义 item
变量,而不是使用“全局”变量(var item = {}
而不是 item = {}
)。这是因为在 IE9 中它似乎是通过引用传递的,因此您推送的是同一个对象,更新了三次(在迭代之间更改其值)。
附言
顺便说一下,您正在使用的其他浏览器似乎在您每次使用 .push
时都会创建一个新变量,我不确定这是“标准”行为。一分给IE9!
关于javascript - 解析数组的 JSON 对象在 IE9 中给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322618/