从其他阵列项目中制作一个数组



我有以下问题:

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'], ...]

我很困惑,就像如何将一个值一起用这些值制作到2D数组中。谢谢

使用JavaScript与某些过度kill:):

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]);
}
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);

最新更新