我正在尝试使用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];
}
});
答案 0 :(得分:6)
您在上一次迭代中未返回任何内容,因此返回值为undefined
,这是错误的,因此.every
将失败-在{{1 }}:
true
或者,没有else
:
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;
}
})
);
答案 1 :(得分:3)
我将为第一个元素返回true
,然后将最后一个与实际元素进行比较。
为什么第一个元素?更容易检查。比较
!index
vs
index !== array.length - 1
您看到的第一张支票比第二张支票要短。
const
nums = [1, 2, 3, 4, 5],
isInOrder = nums.every((num, index, array) => {
if (!index) return true;
return array[index - 1] + 1 === num;
});
console.log(isInOrder);
答案 2 :(得分:0)
在最后一次迭代中,您返回undefined。试试
nums.every( (x,i,a)=> x==a[0]+i )
const nums = [1, 2, 3, 4, 5];
const numsBad = [1, 2, 4, 3, 5];
let test = arr => arr.every( (x,i,a)=> x==a[0]+i )
console.log(test(nums));
console.log(test(numsBad));