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数据类型及判断内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。