四种方式:typeof、instanceof、constructor、object.prototype.toString.call()
一、typeof
直接在计算机底层基于数据类型的值(二进制)进行检测
适合基本数据类型的检测:除null的基本数据类型(string、number、boolean、undefined)
console.log(typeof(1)) //number
console.log(typeof('1')) //string
console.log(typeof(true)) //boolean
console.log(typeof(undefined)) //undefined
为什么除null呢?是因为使用typeOf检测null时,检测结果是对象,因为null和object在计算机中都是以000开的二进制存储,所以检测结果是对象。
console.log(typeof(null)) //object
typeof不能区分普通对象、数组对象、正则对象、日期对象等
console.log(typeof({})) //object
console.log(typeof([])) //object
console.log(typeof(new Date)) //object
二、instanceof检测当前实例是否属于这个类
底层机制:只要当前类出现在实例的原型链上,结果都是true
instanceof不能检测基本数据类型,但是!!instance可以区分对象类型
instanceof运算符会检查原型链。如果对象的原型([[Prototype]])中有构造函数的prototype属性,那么将返回true。
const obj = {};
const arr = [];
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(obj instanceof Array); // false
但是由于我们可以随便改变原型的指向,所以检测出来的结果是不准的
function Animal() {}
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
三、constructor
用起来比instanceof好一点,但是constructor也是可以对边改,检测结果不准
function Car() {}
Car.prototype.constructor = function() {}; // 修改了 prototype 的 constructor 属性
const myCar = new Car();
console.log(myCar.constructor === Car); // false
四、object.prototype.toString.call()(推荐数据类型检测的方法)
object.prototype.toString.call()是标准的检测方法,可检测基本数据类型也可检测因用过数据类型
Object.prototype.toString.call() 方法能提供更精准的类型检测,尤其是在区分数组、正则表达式等时。
const obj = {};
const arr = [];
const regex = /abc/;
console.log(Object.prototype.toString.call(obj)); // "[object Object]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(regex)); // "[object RegExp]"
console.log(Object.prototype.toString.call(1)); //"[object Number]"
console.log(Object.prototype.toString.call('1')); //"[object String]"
console.log(Object.prototype.toString.call(null)); //"[object Null]"
console.log(Object.prototype.toString.call(true)); //"[object Boolean]"
console.log(Object.prototype.toString.call(function(){})); //"[object Function]"

被折叠的 条评论
为什么被折叠?



