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)
可看到输出结果
总结
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)