Javascript:使用嵌套的for循环比较嵌套数组中的元素

时间:2019-10-25 22:14:09

标签: javascript arrays loops multidimensional-array nested

我正在处理一个看起来像这样的数组:

let matrix = [[0,1,1,2], [0,5,0,0], [2,0,3,3]]

我想遍历每个数组并将值与其他数组中的相同元素进行比较,即我想将第0个数组中的第0个元素与第1个和第2个数组中的第0个元素进行比较(在这种情况下,我会分别比较0到0和2)。

我想遍历所有数组,将当前数组中的当前数组元素与以下数组中的对应数组进行比较,即查看此数组的第0个元素,并将其与接下来两个数组中的第0个元素进行比较,然后查看在此数组的第一个元素处进行比较,然后将其与接下来的两个数组中的第一个元素进行比较,依此类推。

Compare the values 0, 0, 2
Then compare 1,5,0
Then compare 1,0,3,
Then compare 2, 0, 3

如何使用嵌套的for循环来做到这一点?有没有更好的方法可以做到这一点而不涉及嵌套的for循环?

1 个答案:

答案 0 :(得分:2)

使用2个for循环:

let matrix = [[0,1,1,2], [0,5,0,0], [2,0,3,3]];

if (matrix.length > 0 && matrix.every(arr => arr.length === matrix[0].length)) {
  // Loop on the length of the first Array
  for (let i = 0; i < matrix[0].length; i++) {
    const valuesToCompare = [];
    // Loop on each Array to get the element at the same index
    for (let j = 0; j < matrix.length; j++) {
      valuesToCompare.push(matrix[j][i]);
    }
    console.log(`Comparing ${valuesToCompare}`);
  }
} else {
    console.log(`The matrix must have at least one Array,
                 and all of them should be the same length`);
}

使用forEachmap (仍然有两个循环,但不太冗长)

let matrix = [[0,1,1,2], [0,5,0,0], [2,0,3,3]];

if (matrix.length > 0 && matrix.every(arr => arr.length === matrix[0].length)) {
  // Loop on the length of the first Array
  matrix[0].forEach((_, i) => {
    // Map each Array to their value at index i
    const valuesToCompare = matrix.map(arr => arr[i]);
    console.log(`Comparing ${valuesToCompare}`);
  });
} else {
    console.log(`The matrix must have at least one Array,
                 and all of them should be the same length`);
}