js的數(shù)據(jù)類型
基本數(shù)據(jù)類型:number , string , boolean , undefined , null , Symbol,
引用數(shù)據(jù)類型:object
NaN 屬于 number;
Function, Array, Date 都屬于 object;
基本數(shù)據(jù)類型除 null 都可以通過 typeof 判斷,引用數(shù)據(jù)類型除 Function 外都返回 Ojbect
let a = 1, b = "2", c = true, d = undefined, e = null, f = Symbol("f"), g = function () {}, h = [], i = new Date() console.log(typeof a) console.log(typeof b) console.log(typeof c) console.log(typeof d) console.log(typeof e) console.log(typeof f) console.log(typeof g) console.log(typeof h) console.log(typeof i)
查看輸出結(jié)果
可以看到 null 的 typeof 是 object , 這屬于歷史bug ,有興趣可以參考《The history of “typeof null” 》
可通過以下方法判斷 null
function checkNull(num) { return num === null }
object 的詳細類型可通過 Object.prototype.toString.call() 判斷
function checkObject(obj) { return Object.prototype.toString.call(obj) } console.log(checkObject(g)) console.log(checkObject(h)) console.log(checkObject(i))
可看到輸出結(jié)果
也可通過構(gòu)造函數(shù) constructor() 判斷
console.log(g.constructor === Function) console.log(h.constructor === Array) console.log(i.constructor === Date)
可看到輸出結(jié)果
總結(jié)
到此這篇關(guān)于js數(shù)據(jù)類型以及其判斷方法的文章就介紹到這了,更多相關(guān)js數(shù)據(jù)類型及判斷內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://segmentfault.com/a/1190000039339683