JavaScript数据类型检测的四种方式

🧐 typeof

console.log(typeof 1);// 'number'
console.log(typeof true);// 'boolean'
console.log(typeof 'str');// 'string'
console.log(typeof []);// 'object'
console.log(typeof function(){});// 'function'
console.log(typeof {});// 'object'
console.log(typeof undefined);// 'undefined'
console.log(typeof null);// 'object'

注意: typeof的返回值是字符串
其中数组对象null都会被判断为’object’

😎 instanceof

instanceof可以正确判断对象的类型,其内部运行机制是判断在原型链中能否找到该类型的原型

console.log(1 instanceof Number);// false
console.log(true instanceof Boolean);// false
console.log('str' instanceof String);// false
console.log([] instanceof Array);// true
console.log(function(){} instanceof Function);// true
console.log({} instanceof Object);// true

instanceof只能正确判断引用数据类型,而不能判断基本数据类型。instanceof运算符可以用来测试一个对象在其原型链中是否存在一个构造函数的prototype属性

😜 constructor

console.log((1).constructor===Number);//true
console.log((true).constructor===Boolean);//true
console.log(('str').constructor===String);//true
console.log(([]).constructor===Array);//true
console.log((function(){}).constructor===Function);//true  
console.log(({}).constructor===Object);//true

constructor有两个作用,一个是判断数据类型,二是对象实例通过constructor对象访问它的构造函数。需要注意,如果创建一个对象来改变它的原型,constructor就不能用来判断数据了:

function Fn(){};
Fn.prototype = new Array();
let f = new Fn();
console.log(f.constructor===Fn);    // false
console.log(f.constructor===Array); // true

😋 Object.prototype.toString.call()

Object.prototype.toString.call()使用Object对象的原型方法toString来判断数据类型:

let a = Object.prototype.toString;
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function(){}));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));

同样是检测对象obj调用toString()方法,obj.toString()的结果和Object.prototype.toString.call(obj)的结果不一样,这是为什么?
这是因为toString是Object的原型方法,而Array,function等类型作为Object的实例,都重写了toString方法。不同的对象类型调用toString()方法时,根据原型链的知识,调用的对应的重写之后的toString方法(function类型返回内容为函数体的字符串,Array类型返回元素组成的字符串…),而不会去调用Object原型上的toString方法(返回对象的具体类型),所以采用obj.toString()不能得到其对象类型,只能将obj转换为字符串类型;因此,在想要得到对象的具体类型时,应该调用Object原型上的toString()方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值