0
1

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.

[JS]様々な値をINT型にキャストするのに、「 | 0 」が便利すぎな件

Last updated at Posted at 2019-07-18

はじめに

Javascriptでキャストする場合に、めっちゃ簡単な方法を聞いたので、ここに共有しておきます。注意点もあるので、使われる方は最後まで読んでください。

何はともあれコード

INT型にキャストした例
console.log('aaa'|0) //  => 0
console.log(null|0) //  => 0
console.log(NaN|0) //  => 0
console.log(false|0) //  => 0
console.log(true|0) //  => 1
console.log(0|0) //  => 0
console.log(1234|0) //  => 1234
console.log('1234'|0) //  => 1234(半角数字ならINT型にしてくれる)

// 注意!!
console.log(9.9999|0) // => 9(少数点以下除外)
console.log('1234'|0) //  => 0(全角数字は0になる)

全て数字にしてくれます。
文字列の数字も、半角であればキャストしてくれます。
なんと、trueは1にしてくれるという、親切っぷり。
もちろん、0は0のままで、当然ながら変数にも使えます。

少数と全角数字の扱いに注意

少数は切り捨てになるようです。
もし、少数が入りそうな変数などに付ける際は、ご注意を。

また、全角数字も0になってしまうので、ご注意を。

以上です。ありがとうございました。

0
1
3

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?