js的數據類型
基本數據類型:number , string , boolean , undefined , null , Symbol,
引用數據類型:object
NaN 屬于 number;
Function, Array, Date 都屬于 object;
基本數據類型除 null 都可以通過 typeof 判斷,引用數據類型除 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)
查看輸出結果
可以看到 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))
可看到輸出結果
也可通過構造函數 constructor() 判斷
console.log(g.constructor === Function) console.log(h.constructor === Array) console.log(i.constructor === Date)
可看到輸出結果
總結
到此這篇關于js數據類型以及其判斷方法的文章就介紹到這了,更多相關js數據類型及判斷內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://segmentfault.com/a/1190000039339683