我正在尝试使用 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/