js检测数据类型的方法
1、typeof 方法
- 在计算机底层基于数据类型的值(二进制)进行检测
- typeof null 检测出是object,由于对象存储在计算机中是以000开始的二进制进行存储,null也是,所以检测出来的结果是对象。
- typeof 检测普通对象、数组对象、正则对象、日期对象都是object
2、instanceof 方法
- 底层机制:只要当前类出现在实例的原型链上,结果都是true
let arr = [];
arr instanceof Array;
arr instanceof RegExp;
arr instanceof Object;
- 由于可以随意修改原型的指向,所以检测出来的结果不准
function Fn(){
this.x = 100;
}
Fn.prototype = Object.create(Array.prototype);
let f = new Fn;
console.log(f instanceof Array);
1 instanceof Number;
3、constructor 方法
let arr = [];
arr.constructor === Array;
arr.constructor === RegExp;
arr.constructor === Object;
let n = 1;
n.constructor === Number;
- constructor 可以随意修改,所以也不准确
Number.prototype.constructor = 'AA';
let n = 1;
n.constructor === Number;
4、Object.prototype.toString.call([value])方法
- 标准检测数据类型的方法:Object.prototype.toString 不是转换为字符串,是返回当前实例所属类的信息
let obj = { name: '张三'};
obj.toString();
Object.prototype.toString.call(1);
Object.prototype.toString.call(NaN);
Object.prototype.toString.call("");
Object.prototype.toString.call(true);
Object.prototype.toString.call(Symbol('xx'));
Object.prototype.toString.call({});
Object.prototype.toString.call([]);
Object.prototype.toString.call(/^$/);
Object.prototype.toString.call(new Date());
Object.prototype.toString.call(function(){});
Object.prototype.toString.call(null);
Object.prototype.toString.call(undefined);