数据类型检测

四种方式: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]"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值