LoginSignup
3
1

More than 5 years have passed since last update.

型変換をまとめる

Last updated at Posted at 2018-08-29

文字列から数値へ

  • Number関数、parseInt、parseFloat
  • イディオム的に変換する方法
  • 文字列の '0' は判定されない
js
const str = '0123';

//関数
Number(str); //123
parseInt(str, 10); //123
parseFloat(str); //123

//文字列から数値への暗黙の型変換
str - 0; //123
str * 1; //123
str / 1; //123
+str; //123 

数値に変換できない文字列を含む型変換

js
const str2 = '123px';

Number(str2); //NaN 文字列を含むとNaNを返す
parseInt(str2, 10); //123 
parseFloat(str2); //123

空文字列を含む型変換

js
const str3 = '';

Number(str3); //0
parseInt(str3, 10); //NaN 
parseFloat(str3); //NaN

parseInt、parseFloatの違い

parseInt

  • parseIntは第一引数に文字列をとり、第二引数で基数(10進数や6進数など)を取る
  • 第一引数で数字とされない文字を認めると、それ以降の文字を無視して、それまでの値を返す
  • 整数を返す

parseFloat

  • 引数として与えられた文字列を解析し浮動小数点を返す
  • 正負記号 (+ か -)、数字 (0-9)、小数点、指数以外の文字があれば、それ以降を無視してそれまでの値を返す

数値から文字列への変換

  • String関数もしくはtoStringメソッドを使う
  • イディオム的に変換する
js
const num = 123;

String(num); //'123'
num.toString(10); //'123'
num + ''; //'123';

ブーリアン型の型変換

  • falseを返すもの
    • 数値0
    • null
    • undefined値
    • 空文字列
    • arr.lengthで中身がないとき
  • trueをかえすもの
    • 数値1
    • 配列(オブジェクト)。空でもtrueが返る。
    • arr.lengthで配列に中身があるとき
js
//真偽値判定関数
function checkBoolean(val) {
    if (val) {
        console.log(val + ' is true');
    } else {
        console.log(val + ' is false');
    }
}

const num = 0;
const num2 = null;
let num3;
const num4 = 1;
const str = '';
const arr = [];
const arr2 = [2,3];

//falseを返すもの
checkBoolean(num);//"0 is false"
checkBoolean(num2);//"null is false"
checkBoolean(num3);//"undefined is false"
checkBoolean(str);//" is false"
checkBoolean(arr.length);//"0 is false"


//trueをかえすも
checkBoolean(num4);//"1 is true"
checkBoolean(arr);//" is true"
checkBoolean(arr2);//"2,3 is true"
checkBoolean(arr2.length);//"2 is true"

ブーリアン、null、undefined型から数値変換

  • trueは1
  • falseは0
  • nullは0
  • undefinedはNaN
js
let a;

a = Number(true); console.log(a); //1
a = Number(false); console.log(a); //0
a = Number(null); console.log(a); //0
a = Number(undefined); console.log(a); //NaN

比較演算子による型変換

  • 比較できない文字列値はNaN
  • undefinedもNaN
  • trueは1
  • falseは0
  • nullは0
js
function checkBoolean(val) {
    if (val) {
        console.log(val);
    } else {
        console.log(val);
    }
}


checkBoolean(1 > 'x');  //false
checkBoolean(undefined > 0);  //false
checkBoolean(true > 0);  //true 
checkBoolean(null < 1);  //true

オブジェクトからの型変換

  • 文字列型は、String関数もしくはtoStringメソッド
  • 数値型は、Number関数もしくはvalueOfメソッド
  • valueOfメソッドは、オブジェクトが基本型のデータの値を持っていればそれを返す。
3
1
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
3
1