如何使用 &&, ||一起

How to use &&, || together

我不知道为什么以下 returns 错误。

var pets = ['cat', 'dog', 'bat'];
console.log(pets.includes(('cat' && 'monkey') || 'bat' ));

由于'bat'在pet数组中,我认为returns是正确的。

知道为什么这不起作用吗?

那是因为('cat' && 'monkey') || 'bat'给出了monkey。它给出 monkey 的原因是因为 'cat' && 'monkey' 表达式的计算结果为 monkey,因为 catmonkey 都已定义并且对两个定义值都使用 && ,它取第二个值,即 monkey。当 'monkey' || 'bat' 被评估时,它给出第一个值 monkey ,因为在这种情况下,这两个值也被定义,但在 || 表达式中,它给出第一个定义的值,即 monkey在这种情况下。

解开谜团,

pets.includes(('cat' && 'monkey') || 'bat');
//becomes
pets.includes('monkey'); //which is false

var pets = ['cat', 'dog', 'bat'];
console.log(('cat' && 'monkey') || 'bat');
console.log(pets.includes(('cat' && 'monkey') || 'bat'));

那是因为 &&|| 是用来比较布尔表达式的。你真正想做的是:

console.log((pets.includes('cat') && pets.includes('monkey')) || pets.includes('bat'));

要真正检查 pets 是否包含另外两个值,您需要一种不同的方法并使用 Array#every and check a single value in the callback with Array#includes.

迭代该值

var pets = ['cat', 'dog', 'bat'];

console.log(['cat', 'monkey'].every(animal => pets.includes(animal)))           // false
console.log(['cat', 'monkey'].every(animal => pets.includes(animal)) || 'bat'); // 'bat'