javascript - 使用 .every 检查数组中的项目是否连续

标签 javascript

我正在尝试使用 Array 的 .every 来查看数组中的项目是否是连续的(1、2、3、4、5)。为什么当其中的所有内容都是 true 时返回 false?

const nums = [1, 2, 3, 4, 5];

nums.every((num, index) => {
  if (index !== nums.length - 1) {
    console.log(num + 1 === nums[index + 1]);
    return num + 1 === nums[index + 1];
  }
});

最佳答案

你在最后一次迭代中没有返回任何东西,所以返回值为 undefined,这是错误的,所以 .every 将失败 - return else 中为 true:

const nums = [1, 2, 3, 4, 5];

console.log(
  nums.every((num, index) => {
    if (index !== nums.length - 1) {
      console.log(num + 1 === nums[index + 1]);
      return num + 1 === nums[index + 1];
    } else {
      return true;
    }
  })
);

或者,没有 console.log:

const nums = [1, 2, 3, 4, 5];

console.log(
  nums.every((num, index) => (
    index !== nums.length - 1
    ? num + 1 === nums[index + 1]
    : true
  ))
);

关于javascript - 使用 .every 检查数组中的项目是否连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157608/

相关文章:

javascript - 当事件附加到文档时获取元素更改的 id

javascript - window.print() 在 IE7 和 IE8 中卡住

javascript - 有没有办法在滚动条上放置标记?

javascript - 如何将 HTMLButtonElement 对象转换为 html 按钮?

javascript - 如何检查 <object> 是否加载失败?

javascript - 压缩 JS 解码器

php - 获取 ajax 成功后的数据

javascript - 单击按钮弹出 div 应位于屏幕中心

javascript - 无法在 for 循环中递增变量计数器

javascript - 变换原点变化延迟