-4

我有以下问题:

var price   = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock   = ['yes','no','no','yes']

我需要对它们进行分组,以便最终输出以以下格式显示在数组中:

var store = [ ['4','kiwi','yes'],['5','orange','no'], ...]

我很困惑如何将一个包含这些值的数组变成一个二维数组。谢谢

4

2 回答 2

3

使用 JavaScript 有点矫枉过正:):

var price   = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock   = ['yes','no','no','yes']

// if the lengths/size of the above arrays are the same
var store = [];
for(var i = 0, len = price.length; i < len; i++) {
  store.push([price[i], produce[i], stock[i]]);
}

// if the lengths/size of the above arrays aren't the same and you want the minimum full entries
var storeMin = [];
for(var i = 0, len = Math.min(price.length, produce.length, stock.length); i < len; i++) {
    storeMin.push([price[i], produce[i], stock[i]]);
}

// if the lenghts/size of the above arrays aren't the same and you want the maximum entries with defaulting missing values to null 
// replace the nulls by any default value want for that column
var storeMax = [];
for(var i = 0, pLen = price.length, prLen = produce.length, sLen = stock.length, len = Math.max(pLen, prLen, sLen); i < len; i++) {
    storeMax.push([pLen>i?price[i]:null, prLen>i?produce[i]:null, sLen>i?stock[i]:null]);
}
于 2012-10-18T00:34:24.207 回答
2
var price   = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock   = ['yes','no','no','yes']
var store = [];
$.each(price,function(ind,elm) {
    store.push([elm,produce[ind],stock[ind]]);
});
console.log(store);
于 2012-10-18T00:03:09.163 回答