所以我有一个看起来像这样的javascript变量
D,CPU_Purchased_ghz,2015-03-19 00:00:00,10.00,2015-03-20 00:00:00,10.00
是否可以拆分成这样的数组:
[
[D,CPU_Purchased_ghz],
[2015-03-19 00:00:00,10.00],
[2015-03-20 00:00:00,10.00]
]
即。我希望能够将其拆分为2个块
答案 0 :(得分:0)
如果您使用的变量实际上是一个数组:
var arr1 = [ "D", "CPU_Purchased_ghz", "2015-03-19 00:00:00", 10.00, "2015-03-20 00:00:00", 10.00 ];
var arr2 = [];
for(var i=0, l=arr1.length; i<l; i++){
arr2.push( [arr1[i], arr1[++i]] );
}
console.log(arr2); // Outputs [ ["D","CPU_Purchased_ghz"], ["2015-03-19 00:00:00",10.00], ["2015-03-20 00:00:00",10.00] ]
答案 1 :(得分:0)
(参见编辑 for Array解决方案)
这可以通过正则表达式很好地完成
var arr = aString.match(/[^,]+,[^,]+/g);
aString
包含您的字符串。
返回:
[
"D,CPU_Purchased_ghz",
"2015-03-19 00:00:00,10.00",
"2015-03-20 00:00:00,10.00"
]
编辑:我刚收到通知,该变量可能是数组而不是字符串。如果确实如此,那么首先加入数组:
var arr = aArray.join(',').match(/[^,]+,[^,]+/g);
答案 2 :(得分:0)
这个小函数会将数组块化为指定大小的块:
var chunk = function (chunkSize, array) {
var chunked = []
var from
for (var i = 0, range = array.length / chunkSize; i < range; i++) {
from = i * chunkSize
chunked.push(array.slice(from, from + chunkSize))
}
return chunked
}
// Usage:
chunk(3, [1, 2, 3, 4, 5])
// -> [[1, 2, 3], [4, 5]]