41
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのチルダ演算子

Posted at

javascriptの「~」チルダ演算子はビット反転演算子で、整数をビット反転させると符号を反転させて1引いた数になる

console.log(~-4); // 3
console.log(~-3); // 2
console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3
console.log(~3);  // -4
console.log(~4);  // -5

上記の通り、-1のときだけ0になる
indexOfが値が存在しない場合に-1を返すので組み合わせると下記のようにできる

var arr = [1,2,3];
if (!~arr.indexOf(0)) {
  // indexが存在しない
}
41
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?