首页 > 解决方案 > Javascript:使用嵌套 for 循环比较嵌套数组中的元素

问题描述

我正在使用如下所示的数组数组:

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

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

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

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

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

标签: javascriptarraysloopsmultidimensional-arraynested

解决方案


使用 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`);
}

使用forEachand (仍然是两个循环,但不那么冗长)map

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`);
}


推荐阅读