我如何比较 2 个不同的数组索引?

How can I compare 2 different arrays index wise?

从索引角度我的意思是:
如果有两个数组 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]))因为你不知道数组可以有多长

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

你只有 return 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版本,但是没有错误检查。它只是 returns 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