js数据类型以及其判断方法实例
作者:REMZ
这篇文章主要给大家介绍了关于js数据类型以及其判断方法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
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数据类型及判断内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
