JavaScript 中检查数组是否不包含某个值
要检查数组是否不包含值,请使用逻辑 NOT ! 运算符来否定对 includes() 方法的调用。 NOT ! 运算符在对真值调用时返回 false,反之亦然。
const arr = ['a', 'b', 'c'];
const notIncludesD = !arr.includes('d');
console.log(notIncludesD); // ?️ true
const notIncludesC = !arr.includes('c');
console.log(notIncludesC); // ?️ false
if (notIncludesC) {
console.log('✅ the value c is NOT included in the array');
} else {
console.log('⛔️ the value c is included in the array');
}
我们使用逻辑 NOT ! 运算符来否定对 Array.includes 方法的调用。
我们的第一个示例检查值 d 是否不包含在数组中并返回 true。
const arr = ['a', 'b', 'c'];
const notIncludesD = !arr.includes('d');
console.log(notIncludesD); // ?️ true
const notIncludesC = !arr.includes('c');
console.log(notIncludesC); // ?️ false
字符串 c 包含在数组中,因此表达式返回 false。
以下是使用逻辑 NOT ! 运算符的更多示例。
console.log(!true); // ?️ false
console.log(!false); // ?️ true
console.log(!'hello'); // ?️ false
console.log(!''); // ?️ true
console.log(!null); // ?️ true
我们可以想象逻辑 NOT ! 运算符首先将值转换为布尔值,然后翻转值。
JavaScript 中的假值有:null 、undefined 、空字符串 、NaN 、0 和 false。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。