JavaScript 判断数据类型
首先JavaScript基本数据类型有:number null undefined string boolean es6以后还新增了bigint和symbol
(上面的都是小写!!!就比如String和string是不一样的 typeof String是function 也就是 大写开头的是js对象 小写的才是类型)
判断类型的方法有:
1、typeof
可判断:number undefined string boolean function
注意:null RegExp []会被判断成object NaN为number。
2、instanceof
在JavaScript中,instanceof运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
通俗地说,主要是检测引用数据类型(但如果了解原型链之后,这句话其实不太准确)
可判断:原型链中的对象(因为是大写的),这里不展开说了,具体可以百度一下原型链
举一些例子吧:
console.log([] instanceof Array);//true
console.log({} instanceof Object);//true
console.log(/\d/ instanceof RegExp);//true
console.log(function(){} instanceof Object);//true
console.log(function(){} instanceof Function);//true
注意:这里Array和RegExp都可以判断,但是无法区别Function,因为原型链的尽头是Object.prototype(有人说是null,其实两种都对),万物皆对象。
3、Object.prototype.toString.call()
该方法可以直接精准区分数据类型,取到的值是[a,RealType],做一个字符串截取+转首字母为小写即可,具体点击下方文章:
https://blog.youkuaiyun.com/weixin_44013946/article/details/119984039
4、constructor
该方法和instanceof相似,涉及原型链,简单点说,返回的是一个对象,可以直接xxx.constructor === Function/Array/Object来判断
不细🔒了 有缘更
最后来个终极判断类型的方法:
https://blog.youkuaiyun.com/weixin_44013946/article/details/120209958