JS波浪符巧用

引用

原文地址: https://khalilstemmler.com/articles/tilde-in-javascript/

起因

源于一段代码

if(~followers.indexOf(target)) {
// do some action
}

深挖

~A 同等于 -(A + 1)

和 JS 的联系

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

只有当 A=-1 的时候 ~A === 0

结果

不用去和 -1 比了!!!

if (!!~fruits.indexOf('apples')) {
// Yay apples
console.log("Found apples!") // <= this will print
}
else {
// Still no apples
console.log("No apples apparently")
}