若資料存在於 array,Array.prototype.indexOf() 會回傳其 index,否則回傳 -1。
Version
macOS Catalina 10.15.2
VS Code 1.41.1
Quokka 1.0.271
ECMAScript 2015
Found
let data = [1, 2, 3]
if (data.indexOf(2) > -1) console.log('found')
if (~data.indexOf(2)) console.log('found')
若 indexOf() 回傳大於 -1 則表示找到,亦可使用 ~,只要不是 -1 都會回傳 true。

Not Found
let data = [1, 2, 3]
if (data.indexOf(4) === -1) console.log('not found')
if (!~data.indexOf(4)) console.log('not found')
若 indexOf() 等於 -1 表示找不到,亦可使用 !~,只要是 -1 都會回傳 true。

Conclusion
- 透過
~與!~轉成 boolean 特性,亦可用於其他回傳-1的 function