javascript原始類型轉換

先看例子

    let a = '5' + '2';
    let b = '5' - '2';
    console.log(a, b);
    //52 3
    let a = '' - 1;
    let b = true + false;
    let c = null + 1;
    let d = undefined + 1;
    let e = [] + [];
    console.log(a, b, c, d, e)
    // -1 1 1 NaN ""

類型轉換場景

  • 轉字符串 經常出現在+運輸符中,並且其中有一個操作符不是數值類型
  • 轉數值 出現在數學運算符中
  • 轉布爾 if 語句及邏輯運算中
  • 相等性(==)
    console.log(null == undefined); // true
    console.log('0' == 0);// true
    console.log(0 == false);// true
    console.log('0' == false);// true
轉字符串 轉數值 轉布爾 轉對象
undefined ‘undefined’ NaN false TypeError
null ‘null’ 0 false TypeError
true ‘true’ 1 new Boolean(true)
false ‘false’ 0 new Boolean(false)
‘’ 0 false new String(’’)
‘1.2’ 1.2 true new String(‘1.2’)
‘abc’ NaN true new String(‘abc’)
[] ‘’ 0 false /
[9] ‘9’ 9 true /
[‘a’,‘b’, …] join方法 NaN true /

js原始類型與對象類型的區別

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章