数据类型检测
-
typeof
- 直接在计算机底层基于数据类型的值(二进制)进行检测的
- null 是一个数据类型,为什么检测出来 “object” 呐???
- 对象存储在计算机中,都是以000开始的二进制存储。null 也是000开始的, typeof 检测出来的结果是对象
- 所以,普通对象/数组对象/正则对象/日期对象,检测出来的都是 “object”
-
instanceof(检测当前实例是否属于这个类的)
-
instanceof 就能解决 typeof 不足之处
-
let arr = []; console.log(arr instanceof Array); // true:由此判断,arr 是一个数组
-
-
instanceof 底层机制,只要当前类出现在实例的原型上,结果都是 true。会带来以下问题
-
function Fn() { this.x = 1; } Fn.prototype = Object.create(Array.prototype) let f = new Fn; console.log(f instanceof Array); //true
-
我们可以随意修改原型的指向,所以检测的结果也不是很准确
-
-
instanceof 还有一个致命的缺点,不能检测基本数据类型
-
console.log(1 instanceof Number); // false
-
-
-
constructor
-
constructor 能检测基本类型,也能检测数组
-
let arr = [], n = 1 console.log(arr.constructor === Array); // true console.log(arr.constructor === Object); // false console.log(n.constructor === Number); // true
-
-
同样,原型中的 constructor 也可以随便改。一些情况下,也是不准确
-
let n = 1; Number.prototype.constructor = 'AA' console.log(n.constructor === Number); // false console.log(n.constructor === 'AA'); //true
-
-
-
Object.prototype.toString.call([value])
-
标准检测数据类型的办法:Object.prototype.toString 不是转换为字符串,是返回当前实例所属类的信息
-
let n = 1, s = '', a = []; console.log(Object.prototype.toString.call(n)); //Number console.log(Object.prototype.toString.call(s)); //String console.log(Object.prototype.toString.call(a)); //Array
-
-
支持检测的类型[Number / String / Boolean / Null / Undefined / Smbol / Object / Array / RegExp / Date / Function]
-
总结
Object.prototype.toString 虽然是万能的,但是代码量太长~过于繁琐。基本类型还是推荐 typeof。打一个单词就可以显示出来数据类型,他不香吗!!!!!