检测数据数据类型的几种方式

本文探讨了JavaScript中如何检测变量的数据类型,包括使用typeof操作符、instanceof运算符和constructor属性,以及利用Object.prototype.toString.call()方法。同时,阐述了基本类型与引用类型的区别,并指出它们在检测中的特点和限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.检验基本类型typeof

console.log(typeof NaN) //number
console.log(typeof "hello")//string
console.log(typeof function(){})//function

//但引用类型和null都是object
console.log(typeof null)
console.log(typeof [])
console.log(typeof {})

2.intanceof检测对象是否是某个类的实例

console.log(123 instanceof Number)//false
let num=new Number(123)
console.log(num instanceof Number)//true
console.log([] instanceof Array)//true
//但所有的引用类型都是Object的实例,也不能检测基本类型0.0
console.log({} instanceof Object)//true
console.log([] instanceof Object)//true
console.log(function(){} instanceof Object)//true

3.利用constructor属性(利用了原型链)

console.log(123 instanceof Number)//false
let num=new Number(123)
console.log(num instanceof Number)//true
console.log([] instanceof Array)//true
//但所有的引用类型都是Object的实例,也不能检测基本类型0.0
console.log({}.constructor == Object)//true
console.log([].constructor == Array)//true
//但只能检测引用数据类型且constructor可以认为改变

4.Object.prototype.toString.call()方法

console.log(Object.prototype.toString.call(123))//[object Number]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值