LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】暗黙的な型変換

Last updated at Posted at 2022-08-10

概要

JavaScriptを学習、理解を深めるため「JavaScript Primer 迷わないための入門書」を読み、
理解した内容等を記載していく。

【JavaScript】JavaScript入門一覧」に他の記事をまとめています。

この記事で理解できること

  • 暗黙的な型変換とは
  • 明示的な型変換方法

暗黙的な型変換とは

  • ある処理過程で意図していない明示的ではない型変換が行われること。
  • 演算子による演算や、関数内での処理中に行われる。
パターン 特性
等価演算子(==)での比較 オペランドを同じ型となるように変換する
プラス演算子(+)で数値と文字列を処理 数値 -> 文字列へと変換する
マイナス演算子(-)で数値と文字列を処理 文字列 -> 数値へと変換する

等価演算子(==)での比較

  • 暗黙的な型変換による予測不可能な結果のパターン数が多く、把握は現実的ではない。
  • 等価演算子より厳密等価演算子(===)での比較が推奨される。
// 例:文字列と数値を比較
console.log("1" == 1);  // => true(暗黙的に型が同じになるよう変換されている)

// 参考:厳密等価演算子(===)での比較
console.log("1" === 1); // => false

プラス演算子(+)での比較

  • 文字列としての結合が優先されるため、数値が文字列へと変換される
// 例:文字列と数値を比較
console.log("2" + 1);  // => 21

マイナス演算子(-)での比較

  • 文字列に対するマイナス演算子の定義がないため、文字列が数値へ変換される
// 例:文字列と数値を比較
console.log("2" - 1);  // => 1

明示的な型変換

  • 演算対象に異なるデータ型の値が混ざっているオペランドが3つ4つとなった場合、さらに複雑となり、演算する順番によっても結果が変わってくる。
  • 暗黙的な型変換による想定外の結果が発生することを避けるには、明示的に型変換を行う。
// 例:異なるデータ型の値を持つオペランドが3つの場合
console.log(1 + "2" + 3); // => 123
console.log(1 + 2 + "3"); // => 33

任意の値を真偽値へ変換

  • Booleanコンストラクタを使用する。
  • falsyな値false、それ以外はtrueになる。
// falsyな値はfalseになる
console.log(Boolean(false));        // => false
console.log(Boolean(0));            // => false
console.log(Boolean(-0));           // => false
console.log(Boolean(0n));           // => false
console.log(Boolean(""));           // => false
console.log(Boolean(null));         // => false
console.log(Boolean(undefined));    // => false
console.log(Boolean(NaN));          // => false

// falsyな値以外はtrueになる
console.log(Boolean(true));         // => true
console.log(Boolean(1));            // => true
console.log(Boolean("1"));          // => true
console.log(Boolean({}));           // => true

数値を文字列へ変換

  • Stringコンストラクタを使用する。
  • 数値以外にも使用できるが、プリミティブ型の値にのみ使用することが推奨される。
    (配列やオブジェクトにはそれぞれに適切な方法があるため)
// プリミティブ型の値
console.log(String("str"));                         // => "str"
console.log(String(true));                          // => "true"
console.log(String(null));                          // => "null"
console.log(String(undefined));                     // => "undefined"
console.log(String(Symbol("シンボルの説明文")));       // => "Symbol(シンボルの説明文)"

// プリミティブ型以外の値
console.log(String([1, 2, 3]));                     // => "1,2,3"
console.log(String({ key: "value" }));              // => "[object Object]"
console.log(String(function() {}));                 // "function() {}"

// 参考:配列、オブジェクトをより適切な方法で値を返す
console.log([1, 2, 3].join(','));                   // => "1,2,3"
console.log(JSON.stringify({ key: "value"}));       // => {"key":"value"}

文字列を数値へ変換

  • Numberコンストラクタを使用する。
  • 数値へ変換できない値はNaNへ変換される。
    (どの数値とも一致しない特性を持つが、Number型の値を表現しているもの)
  • Numberオブジェクトには、文字列から数字を取り出すNumber.parseIntNumber.parseFloat関数が存在する。
// 文字列を数値へ変換
console.log(Number("1"));                           // => 1
console.log(Number("A"));                           // => NaN

// parseIntは文字列から整数を取り出す
console.log(Number.parseInt("100歳"));              // => 100

// parseFloatは文字列から浮動小数点数を取り出す
console.log(Number.parseFloat("0.5px"));            // => 0.5
0
0
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
0