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

これらの値を使用して 1 つの配列を 2 次元配列にする方法と同じくらい混乱しています。ありがとう

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 に答える