indexOf 的按位操作简化

在查找数组的某个值时,我们可以使用 indexOf() 方法。但有一种更好的方法,让我们来看一下这个例子。

//longhand
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

按位 (~) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。

if (arr.includes(item)) { 
// true if the item found
}
原文地址:https://www.cnblogs.com/konglxblog/p/15757743.html