LoginSignup
21
18

More than 5 years have passed since last update.

JavaScriptで知ってHappyになる型変換

Last updated at Posted at 2012-12-26

Stringでキャストする

// 空の文字列の付加により値を簡単に文字列にキャストできます。
'' + 10 === '10'; // true

Numberでキャストする

// 単項プラスオペレーターを使うと数値にキャストすることができます。
+'10' === 10; // true
+'010' === 10; // true
Number('010') === 10; //true ※Numberの前にnewを使っていないことに要注意。
parseInt('010', 10) === 10; //true ※引数の10は10進数の意味です。

+'010.2' === 10.2 // true
Number('010.2') === 10.2 // true ※Numberの前にnewを使っていないことに要注意。
parseInt('010.2', 10) === 10 // true ※引数の10は10進数の意味です。

Booleanでキャストする

// notオペレーターを2回使うと、値はブーリアンに変換できます。
// 「!!0」、「!!''」と「!!false」以外は全部trueになっていますね
!!'hoge';  // true
!!'';      // false
!!0;       // false
!!'0';     // true
!!1;       // true
!!'1';     // true
!!-1;      // true
!!'-1';    // true
!!{};      // true
!!true;    // true
!!'true';  // true
!!false;   // false
!!'false'; // true
21
18
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
21
18