我正在尝试使用由传入的JSON表创建的动态表。
JSON表遵循以上格式:
[timestamp, value1, value2, value3, value4]
值的数量没有修复,一个查询可以返回4个值,下一个5,6,7 ... 表格来自表格数据
下面的代码尝试创建另一个表,如下所示:
s[1] = [Timestamp, value1]
s[2] = [Timestamp, value2]
s[3] = [Timestamp, value3]
....
这是代码
var s = new Array();
for (var i = 0; i < data.length-1; i++) {
var myrow = String(data[i]);
var l = (myrow.match(/,/g) || []).length + 1
var myarr = myrow.split(",");
for (var j = 1; j < l; j++){
if (isNaN(s[j])) {
s[j] = new Array(2);
}
if (parseFloat(myarr[j]) != 0){
s[j].push([parseInt(myarr[0]), parseFloat(myarr[j])]);
}
}
但是当我执行这段代码时,我所有的[j]都是NaN。
以下是我希望得到的一个例子:
//first iteration
data = ["1413370800000", "68.400580793576", "35.854875270197", "0"]
timestamp = 1413370800000
value1 = 68.400580793576
s[1] = [1413370800000, 68.400580793576]
timestamp = 1413370800000
value2 = 35.854875270197
s[2] = [1413370800000, 35.854875270197]
timestamp = 1413370800000
value3 = 0
s[3] = [1413370800000, 0]
//second iteration
data = ["1413356400000", "125.99187714667", "19.503481981345", "138.13301276328"]
s[1] = [[1413370800000, 68.400580793576], [1413356400000, 125.99187714667]]
s[2] = [1413370800000, 35.854875270197], [1413356400000, 19.503481981345]]
s[3] = [1413370800000, 0], [1413356400000, 138.13301276328]]
你可以帮帮我吗?
谢谢
答案 0 :(得分:0)
这个怎么样:
data = ["1413370800000", "68.400580793576", "35.854875270197", "0"]
ts = new Date(parseInt(data.shift())); // or whatever...
data2 = data.map(function(x) {
return [ts, parseFloat(x)];
});
document.write(JSON.stringify(data2));
通常,Javascript iteration methods会导致代码比裸循环更简单,更易读。
答案 1 :(得分:0)
至于georg的答案,但使用for循环(假设你想要将字符串转换为Numbers):
data = ["1413370800000", "68.400580793576", "35.854875270197", "0"]
for (var i=1, data2=[]; i<data.length; i++) {
data2.push([+data[0], +data[i]]);
}