为什么array . prototype .every()带大括号返回false而不带大括号返回true ?



我在一个项目上工作时遇到了一个问题,我注意到这是由于我的函数中的花括号…简单的例子

const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];
const isPresentInBothArrays1 = array2.every((number)=>{
array1.includes(number);
});
console.log(isPresentInBothArrays1) //prints false;
const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));
console.log(isPresentInBothArrays2) //prints true;

为什么isPresentInBothArrays1带花括号返回false和IsPresentInBothArrays2不带花括号还真吗?

这是因为箭头函数的语法,如果你这样写:

(param1, param2) => {//some expression}

等价于:

function f(param1, param2) {
// some expression
}

,因为它没有显式的返回语句,默认情况下它将返回undefined

但是,如果省略花括号并放入单个表达式,则该表达式将作为快捷方式,并返回该表达式的值作为函数的返回值。

因此,对于您在第一种形式中的问题,它将从计算为false的函数返回undefined,这不是您想要的,但第二种形式正确返回一个布尔值,指示该值的存在。

如果使用花括号,则需要添加return:

const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];
const isPresentInBothArrays1 = array2.every((number)=>{
return array1.includes(number);
});
console.log(isPresentInBothArrays1) //prints true;
const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));
console.log(isPresentInBothArrays2) //prints true;

如果省略花括号,箭头函数将隐式返回=>之后的表达式的结果。

然而,如果你使用花括号,你需要写return来让它返回一些东西,否则,它将返回undefined

所以,在这个特殊的例子中,你需要写:

const isPresentInBothArrays1 = array2.every(number => {
return array1.includes(number);
});

如果您出于任何原因想要使用大括号

最新更新