先补充一下基础知识:数据类型
数据类型分为:基础数据类型和引用数据类型
基础数据类型常见有:string、number、boolean、null、undefined、symbol(不常用)
引用数据类型常见有:object、array、function
1、常用判断数据类型为 typeof和 instanceof
-
typeof
判断一个值,返回一个字符串
typeof '0' // 'string' typeof 0 // 'number' typeof true // 'boolean' typeof null // 'object' typeof undefined // 'undefined' typeof Symbol() // 'symbol' typeof [] // 'object' typeof {} // 'object' typeof new Function() // 'function'
结论:
- 优点:
- 在基本数据类型中可以看出,除 null以外的类型都为可以直接判断出
- 在引用数据类型中可以看出,除function可以直接判断以外,其他的无法直接判断
- 对于null 的判断 直接 使用 全等 ===
- 缺点
- 无法判断引用类型中的array 和object 两种类型
-
instanceof
原理:判断 构造函数的原型 是否 出现在实例对象的原型链上
先简单补充一下基础知识:构造函数、原型、实例对象、原型链之间的关系。
跳转:原型及原型链详解function G_vespa(name){ // 构造函数 this.name=name } G_vespa.prototype.age='18' // 原型 const vespa1=new G_vespa('小龚') // 实例对象 console.log(vespa1.name) // '小龚' console.log(vespa1.age) // 先找实例对象上的属性,没有; 继续在实例对象的继承原型链上找属性 '18'
使用方式:left instanceof right ,返回一个boolean 值。
'0' instanceof anytype // false let str=new String() str instanceof String // true 0 instanceof anytype // false let num=new Number(0) num instanceof Number // true {} instanceof Object //true let _obj=new Object() _obj instanceof Object // true [] instanceof Array //true let _array=new Array() _array instanceof Array // true let fun1=function(){} fun1 instanceof Function //true let fun2=new Function() fun2 instanceof Function // true
结论:
- 优点
- instanceof 可以判断引用类型
- 缺点
- 无法准确的判断基本数据类型(可以判断通过构造函数创建的变量)
总结:两种类型的判断都有一定的优缺点,可根据实际场景使用。
2、优化使用Object.proptotype.toString()
Object.prototype.toString()
返回"[object Type]"
,这里的Type
是对象的类型。call 可替换为apply (传入一个参数并调用) 跳转:call、apply、bind详解
const arr = [1, 2, 3]; arr.toString(); // "1,2,3" Object.prototype.toString.call(arr); // "[object Array]" Object.prototype.toString.apply(arr); // "[object Array]"