【问题标题】:How can I compare 2 different arrays index wise?如何比较 2 个不同的数组索引?
【发布时间】:2021-05-07 14:34:29
【问题描述】:

从索引方面我的意思是:
如果有两个数组AB,则数组A 中索引0 处的项与数组B 中索引0 处的项进行比较。

以下是要处理的示例:

let start = ['m', 'y', 'a', 'g', 'e', 'i', 's'];

let end = ['y', 'm', 'a', 'g', 'e', 'i', 's'];

你千万不能这样((a[1] === b[1])),因为你不知道数组能有多长

【问题讨论】:

标签: javascript arrays comparison


【解决方案1】:

您可以使用标准的 for 循环来迭代 start(或 end)数组的索引。循环时,您可以检查该索引处每个数组的值并进行比较。

如果你没有提前退出函数,你只会返回true

function areEqual(start, end) {
  if (start === end) {
    return true; // Same memory address
  }
  if (start.length !== end.length) {
    console.error('Length of arrays do not match!');
    return false;
  }
  for (let index = 0; index < start.length; index++) {
    if (start[index] !== end[index]) {
      console.error(`Values at index ${index} do not match`);
      return false;
    }
  }
  return true; // Equal!
}

const start = ['m', 'y', 'a', 'g', 'e', 'i', 's'];
const end = ['y', 'm', 'a', 'g', 'e', 'i', 's'];

console.log(areEqual(start, end));

这是一个 ES6 版本,但它没有错误检查。它只返回truefalse

const
  start    = ['m', 'y', 'a', 'g', 'e', 'i', 's'],
  end      = ['y', 'm', 'a', 'g', 'e', 'i', 's'],
  other    = ['m', 'y', 'a', 'g', 'e', 'i', 's'],
  areEqual = (a, b) =>
               (a === b) || (a.length === b.length && !a.some((x, i) => x !== b[i]));

console.log(areEqual(start, end));   // Diff  -- false
console.log(areEqual(start, start)); // Same  -- true
console.log(areEqual(start, other)); // Equal -- true

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    相关资源
    最近更新 更多