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

2022-04-15 0 1,067

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)

查看输出结果

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

可以看到 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))

可看到输出结果

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

也可通过构造函数 constructor() 判断

console.log(g.constructor === Function)
console.log(h.constructor === Array)
console.log(i.constructor === Date)

可看到输出结果

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

总结

到此这篇关于js数据类型以及其判断方法的文章就介绍到这了,更多相关js数据类型及判断内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript js数据类型以及其判断方法实例 https://www.niceym.com/32003.html