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原始类型与对象类型的区别

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