js数据类型及判断 js数据类型以及其判断方法实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js数据类型及判断 js数据类型以及其判断方法实例

REMZ   2021-03-05 我要评论
想了解js数据类型以及其判断方法实例的相关内容吗,REMZ在本文为您仔细讲解js数据类型及判断的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js数据类型判断,js判断是不是数组,javascript的数据类型,下面大家一起来学习吧。

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)

可看到输出结果

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们