JavaScriptのデータ型と型変換について解説します。
数値から文字列に変換
Stringクラスの引数に渡す
var num = 100; var str = String(num);
toStringメソッドを使用する
var num = 100; var str = num.toString();
undefined,nullから文字列に変換
toStringメソッドの場合
var num1 = undefined;
console.log(num1.toString());
結果:Cannot read property ‘toString’ of undefined
console.log(num1.toString());
結果:Cannot read property ‘toString’ of undefined
var num2 = null;
console.log(num2.toString());
結果:Cannot read property ‘toString’ of null
console.log(num2.toString());
結果:Cannot read property ‘toString’ of null
Stringクラスの場合
var num1 = undefined;
console.log(String(num1));
結果:undefined
console.log(String(num1));
結果:undefined
var num2 = null;
console.log(String(num2));
結果:null
console.log(String(num2));
結果:null
データ値 | Stringクラス | toStringメソッド |
undefined | undefined | エラー |
null | null | エラー |