【问题标题】:Javascript: Comparing elements in nested arrays using nested for loops [closed]Javascript:使用嵌套的for循环比较嵌套数组中的元素[关闭]
【发布时间】:2020-02-22 06:27:29
【问题描述】:

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

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 个元素处,并将其与接下来的两个数组中的第 1 个元素进行比较,依此类推。

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

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

【问题讨论】:

  • @Tibike 这不是比较两个数组,而是比较同一个数组中的行。
  • 比较所有元素是什么意思?你想打印它们是否都一样?
  • 这是我第二次询问关于比较相同嵌套数组中的元素(但在父数组中的不同数组中)的问题,第二次我被否决并提到了一篇关于比较两个不同的嵌套数组。非常令人沮丧。

标签: javascript arrays loops multidimensional-array nested


【解决方案1】:

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

【讨论】:

  • 你实际上并没有比较任何东西。
  • OP 没有说应该如何比较它们以及输出应该是什么。我选择不去猜测,只回答关于循环的问题。
  • 循环对我有用。早些时候我有一个非常相似的方法,但事实证明我有 matrix[j][i] 部分向后并且正在做 matrix[i][j] 这就是我未定义错误的原因。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2016-06-01
  • 2020-02-16
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2018-11-11
相关资源
最近更新 更多