简体   繁体   English

如何在每次迭代后将新列添加到 javascript 中的二维数组?

[英]How can i add new column to a 2D array in javascript after each iteration?

I have 2 arrays.我有 2 个 arrays。 (arr1, arr2) I want to take the value at index 0 and multiply it by each value in arr2, and add each value to a new row in a 2D array. (arr1, arr2) 我想将索引 0 处的值乘以 arr2 中的每个值,然后将每个值添加到二维数组中的新行。 ex.前任。

arr1 = [1,3,5,7] arr2 = [4,2,1,6]

Outcome should be:结果应该是:

 2Darray = [
   [4,12,20,28],
   [2,6,10,14],
   [1,3,5,7],
   [6,18,30,42] 
];

Im having trouble with the for loop in javascript and how to create a new row after each iteration.我在 javascript 中的 for 循环以及如何在每次迭代后创建新行时遇到问题。 ``` ```

Thanks谢谢

You could map the arrays with the product of the values.您可以将 map arrays 与这些值的乘积。

 const array1 = [1, 3, 5, 7], array2 = [4, 2, 1, 6], result = array2.map(v => array1.map(w => v * w)); result.map(a => console.log(...a)); console.log(result);

Using map like others said would be best.像其他人所说的那样使用 map 是最好的。

Using the remainder operator(%) makes the most sense in my head:使用余数运算符(%)在我的脑海中最有意义:

const arr1 = [1,3,5,7];
const arr2 = [4,2,1,6];

var twoDemArray = [];

for (var i = 0; i < arr1.length; i++) {

  let tempArr = [];
  
  for (var j = 1; j < arr2.length+1; j++) {
    let newNum = arr1[i]*arr2[j-1];

    tempArr.push(newNum);
    
    if (j % arr2.length == 0) {
      twoDemArray.push(tempArr);
      tempArr = [];
    };
  };

};

console.log(twoDemArray)
//do stuff with twoDemArray

Mapping over both arrays helps.映射两个 arrays 有帮助。

 arr1 = [1,3,5,7]; arr2 = [4,2,1,6]; let res = arr2.map(a2 => arr1.map(a1 => a1*a2)) console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM