數據檢測類型
經常會遇到檢測數據類型的問題,這裏歸納總結一下。
檢測類型
1.typeof
常用於檢測基本數據類型,但是 null 和 Array 類型不起作用,會返回 Object
typeof undefined //undefined
typeof null //object
typeof true //boolean
tyoeof '' //string
typeof [] //object
typeof function(){} //function
typeof {} //object
2.Object.prototype.toString.call()
每種內置對象都定義了 [[Class]] 內部屬性的值,用於內部區分對象的種類,我們不能直接訪問這個屬性,但是我們可以通過一種方法訪問,Object.prototype.toString.call
Object.prototype.toString.call(null)
//'[object Null]'
Object.prototype.toString.call(undefined)
//'[object Undefined]'
Object.prototype.toString.call(Math)
//'[object Math]'
Object.prototype.toString.call({})
//'[object Object]'
Object.prototype.toString.call([])
//'[object Array]'
Object.prototype.toString.call(new Date)
//"[object Date]"
該屬性是不可更改的,所以十分可靠
檢測實例
3.constructor
可更改的屬性,十分不可靠
4.instanceof
常用於判斷是否是某個對象的實例。
-
不能判斷 null 和 undefined(會報錯)
-
用對象字面量創建的基本數據類型不屬於對象類型
1 instanceof Number //false '' instanceof String //false new Number(1) instanceof Number //true new String('') instanceof String //true
在 child instanceof super 中,實質是判斷 super.prototype 是否在 child 的原型鏈上(這樣判斷實例並完全不可靠)。
5.isPrototypeOf
ES 6 判斷是否是某個對象的實例,十分可靠。
super.isPrototypeOf(child)
檢測空對象
1.JSON.stringify(data) == “{}”
2.Object.keys(obj).length==0