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数据类型及判断内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
JavaScript判断一个字符串是否包含指定子字符串的方法
这篇文章主要介绍了JavaScript判断一个字符串是否包含指定子字符串的方法,实例分析了javascript字符串操作的技巧,非常具有实用价值,需要的朋友可以参考下2015-03-03
JS组件中bootstrap multiselect两大组件较量
这篇文章主要介绍了JS组件中bootstrap multiselect两大组件,两者之间的较量,优缺点比较,感兴趣的小伙伴们可以参考一下2016-01-01


最新评论