Javascript - 在多维数组中动态创建多个数组

时间:2014-12-19 18:43:39

标签: javascript arrays multidimensional-array

我有一个变量$arrayQuantity,它有一个动态值。它指定了数量 当页面加载时,item数组内部会创建$itemsContainer个数组。

例如:

   //Here I specified to create 3 `item` arrays inside the *itemsContainer* array.
   //The arrays to be created within the *itemsContainer*, contains two
   //dynamic values, `object_name` and `quantity`.

   var object_name;
   var quantity;
   var item = [object_name, quantity];
   var arrayQuantity = 3; 
   var itemsContainer = [];

   //Below is the array created filled with dynamic data.
   itemsContainer = [["Chair", "2"]["Table", "5"]["Glass", "8"]];

采用此解决方案的方法是什么?

编辑:

根据屏幕上按下的按钮,为object_namequantity分配动态数据。 (与问题无关)。

如果数组中存在object_name,则只需更新quantity(防止重复object_name

2 个答案:

答案 0 :(得分:0)

虽然我不确定您从何处获取数据以分配给值object_namequantity ...您可能只需创建一个迭代arrayQuantity次的循环并将一个新数组推送到itemsContainer

var arrayQuantity = 3;
var itemsContainer = [];

for(var i=0; i < arrayQuantity; i++) {
    var arrItem = ["itemName", Math.floor((Math.random() * 10) + 1)];
    itemsContainer.push(arrItem);
}

console.log(itemsContainer);

如果不知道从哪里获得价值,我希望这有助于您找到正确的方向。

>> JSFiddle Example

-mbp

答案 1 :(得分:0)

您创建内部数组,并将其推入外部数组

var objs = ["Chair", "Table", "Glass"];   
var quantities = ["2", "5", "8"]
var itemsContainer = [];
var arrayQuantity = 3; 
for (var i = 0; i < arrayQuantity; i++) {
    var object_name = objs[i];
    var quantity = quantities[i];
    var item = [object_name, quantity];
    itemsContainer.push(item);
}
console.log(itemsContainer);

这是一种更先进的方式https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var objs = ["Chair", "Table", "Glass"];   
var quantities = ["2", "5", "8"]
var itemsContainer = objs.map(function(obj, index){
    return [obj, quantities[index]];
});

如果您想更新特定项目,可以执行以下操作

var object_name = "Chair";
var quantity = "99999";
for (var i = 0; i < itemsContainer.length; i++) {
    if (itemsContainer[i][0] === object_name) {
        itemsContainer[i][1] = quantity;
    }
}