JavaScript數據類型全都知道了麼?

數據類型的分類和判斷

分類

  • 基本(值)類型
    • Number ----- 任意數值 -------- typeof
    • String ----- 任意字符串 ------ typeof
    • Boolean ---- true/false ----- typeof
    • undefined — undefined ----- typeof/===
    • null -------- null ---------- ===
  • 對象(引用)類型
    • Object ----- typeof/instanceof
    • Array ------ instanceof
    • Function ---- typeof

判斷

  • typeof
    • 可以判斷: undefined/ 數值 / 字符串 / 布爾值 / function
    • 不能判斷: null與object object與array
  • instanceof
    • 判斷對象的具體類型
  • ===
    • 可以判斷: undefined, null

instanceof判斷是否屬於某個對象的實例

var b1={
    b2: [1,2,"asd"],
    b3: function () {
    	console.log('b3')
    	return function () {
        	return 'zhang'
      	}
    }
}
console.log(b1 instanceof Object, b1 instanceof Array) // true  false
console.log(b1.b2 instanceof Array, b1.b2 instanceof Object) // true true
console.log(b1.b3 instanceof Function, b1.b3 instanceof Object) // true true
console.log(typeof b1.b3==='function') // true
console.log(typeof b1.b2[2]==='function') // true
b1.b2[2](321) // 321
console.log( b1.b3()() ) // zhang

undefined與null的區別?

  • undefined代表定義未賦值
  • nulll定義並賦值了, 只是值爲null

什麼時候給變量賦值爲null呢?

  • 初始賦值, 表明將要賦值爲對象
  • 結束前, 讓對象成爲垃圾對象(被垃圾回收器回收)

嚴格區別變量類型與數據類型?

  • 數據的類型
  • 基本類型
  • 對象類型
  • 變量的類型(變量內存值的類型)
  • 基本類型: 保存就是基本類型的數據
  • 引用類型: 保存的是地址值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章