我有以下数组:
var dates = new Array();
var answers = new Array();
一旦填充,它们将具有相同的长度。我需要的是一个数组,它将数组的相同索引值配对。像这样:
var pairedArray = new Array();
//pairedArray should have the form: [[dates[0], answers[0]], [dates[1], answers[1]], ...., [dates[n-1], answers[n-1]]]
例如
data: [
[Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
考虑到我有两个相同长度的数组,答案和日期已经填充,这怎么可能呢?
如果您知道它们总是相同的长度,只需循环通过一个并将两者添加到结果中:
var data = [];
for(var i=0; i<dates.length; i++){
data.push([dates[i], answers[i]]);
}
var data = $.map(dates, function(v,i) { return [ [ v,answers[i] ] ]; });
您可以使用jQuery.map()
[docs]方法,但您需要对返回的Array进行双重包装,因为当$.map
获得Array时,它会执行concat
。
var firstArray = ...
var secondArray = ...
if (firstArray.length === secondArray.length) {
var result = [];
for (var i = 0; i < firstArray.length; i++) {
result.push({ [ firstArray[i], secondArray[i] ] });
}
// TODO: do something with the result
}
试试这个
var dates = new Array();
var answers = new Array();
var pairedArray = new Array();
$.each(dates, function(i){
pairedArray.push([ dates[i], answers[i] ]);
});