1. 程式人生 > 實用技巧 >JS進階(一)資料型別與隱式轉換

JS進階(一)資料型別與隱式轉換

1)基本資料型別

string、 number、null、undefined、 boolean、bigInt、symbol

Number型別中NaN不是有效數字但是屬於Number型別,typeof NaN  //=> 'number'
NaN === NaN  // => false
Object.is(NaN,NaN)  // => true
BigInt出現的意思是保證超出最大最小安全值仍然可以準確計算
console.log(Number.MAX_SAFE_INTEGER); //=>9007199254740991
console.log(Number.MIN_SAFE_INTEGER); //=>-9007199254740991
9007199254740991n  =>bigint型別的

(2)引用資料型別【2】

  • object
  • 普通物件 {}
  • 例項物件 new xxx
  • 日期物件 new Date
  • 正則物件 new RegExp
  • 原型物件 prototype
  • 陣列物件 Set Array
  • ....
  • function

2.資料型別的檢測

1.typeof
能檢測基本型別和函式型別,但是對於物件型別和null不能區分(null為計算機歷史遺留問題)
typeof function(){} // ‘function’
typeof NaN // ‘number’
2.constructor
[].constructor === Array
3.instanceof
4.Object.prototype.toString.call()
Object.prototype.toString.call([]) // “[object Array]”

3.資料型別的隱式轉換

(1)轉化為Number型別的情況

  • 使用Number顯式型別轉換, 轉換過程中,遇到物件會先toString然後在Number轉換

  • 例子:
    Number()、Number(null)、Number("")、Number(false) 結果為 0
    Number(undefined) 、 Number({})、 Number(‘wds’), 結果為 NaN
    Number(true) , 轉化結果為 1
    Number([‘2222’]) 結果為 2222
    Number([‘2222’,‘1111’]) 結果為NaN

    Number(‘1,2’)
    ————————————————

  • 使用加號減號等運算子隱式轉換, 轉換過程中,遇到物件會先toString然後在Number轉換

  • 例子:
    
    ‘123’ 結果為 123
    [] 、+null、+false 結果為 0
    {}、+ ‘abc’ 、+ undefined 結果為 NaN
    true 結果為 1
    1 + true 結果為 2
    注意⚠️: NaN + 任何數都是NaN、字串和物件除外,會轉成字串拼接
    NaN+123、NaN+ true、NaN+NaN 結果都為NaN
    NaN + {} 結果為 “NaN[object Object]”
    NaN + [] 結果為 “NaN”
    

    使用isNaN進行檢測的時候,會隱式轉換為數字在檢測,轉換過程中,遇到物件會先toString然後在Number轉換