如何设置带索引的二维数组?

问题描述 投票:0回答:1

我正在尝试用索引名称填充我的二维数组:


    let item = [[],[]];
 
    item = [i]['name': item_name, 'price': price_var, 'quantity': quantity_var] // big ?   

我如何像这样分配我的数组?

。 。 .

这就是我需要它的目的:

所以我用 JS 编写数据层,为此我需要以某种方式创建一种地图,如下所示:


    [0]  ['name': item_name, 'price': price_var, 'quantity': quantity_var]
    [1]  ['name': item_name, 'price': price_var, 'quantity': quantity_var]
    [2]  ['name': item_name, 'price': price_var, 'quantity': quantity_var]
    [...]['name': item_name, 'price': price_var, 'quantity': quantity_var]

每个项目“0”都有自己的属性(名称,价格,数量),我想构建一个响应式项目列表:


    "items": [function() {
    return {
     "name":item_name,
     "price": price_var,
     "quantity": quanitity_var
}}

//tryed this:
let item_name = "shirt";
let price_var = 9.99;
let quantity = 2;

item = [0]['name': item_name, 'price': price_var, 'quantity': quantity_var]

//expecting to be filled

[0]['name': shirt, 'price': 9.99, 'quantity': 2]
javascript arrays multidimensional-array ecmascript-6
1个回答
0
投票

您需要两个循环才能实现这一点。一种用于迭代行,另一种用于迭代列。请参考以下代码:

const rows = 3;
const cols = 3;


const twoDArray = [];


for (let i = 0; i < rows; i++) { // to iterate through rows
  const row = [];
  for (let j = 0; j < cols; j++) { // to iterate through columns
    const item = {
      name: `item_${i}_${j}`,  // Replace this your values
      price: Math.random() * 100, // Replace this your values
      quantity: Math.floor(Math.random() * 10) + 1 // Replace this your values 
    };
    row.push(item);
  }
  twoDArray.push(row);
}


console.log(twoDArray);

注意:如果您需要将实际值传递到每个索引中,您可能必须相应地重构以下代码块:

const item = {
          name: `item_${i}_${j}`,  // Replace this your values
          price: Math.random() * 100, // Replace this your values
          quantity: Math.floor(Math.random() * 10) + 1 // Replace this your values 
        };
© www.soinside.com 2019 - 2024. All rights reserved.