判断数据类型的几种方式
- typeof
- instanceof
- Object.prototype.toString
typeof
typeof 一般被用于判断一个变量的类型,我们可以利用 typeof 来判断 number, string, object, boolean, function, undefined, symbol 这七种类型
console.log(typeof 1);
console.log(typeof '1');
console.log(typeof true);
console.log(typeof false);
console.log(typeof null);
console.log(typeof undefined);
console.log(typeof {});
console.log(typeof []);
console.log(typeof function () {});
console.log(typeof (() => {}));
console.log(typeof Symbol());
由于 js 底层存储数据类型的时候是在变量的机器码的低位 1-3 位存储其类型信息
- 000:对象
- 010:浮点数
- 100:字符串
- 110:布尔
- 1:整数
null 所有机器码都是 0
undefined 用 2^30 表示
所以 null 判断的时候就会变成 object
instanceof
用来判断 object,是哪一种
instanceof 来判断对象的具体类型, instanceof 作用是判断一个实例是否属于某种类型
let person = function () {};
let nicole = new person();
nicole instanceof person; // true
instanceof 也可以判断一个实例是否是其父类型或者祖先类型的实例
let person = function () {};
let programmer = function () {};
programmer.prototype = new person();
let nicole = new programmer();
nicole instanceof person; // true
nicole instanceof programmer; // true
实现原理
先找到右侧的原型 然后在左侧的原型链上进行比对是否相等
function new_instance_of(leftVaule, rightVaule) {
let rightProto = rightVaule.prototype; // 取右表达式的 prototype 值
leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
while (true) {
if (leftVaule === null) {
return false;
}
if (leftVaule === rightProto) {
return true;
}
leftVaule = leftVaule.__proto__;
}
}
Object.prototype.toString
精准判断
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call('hi'); // "[object String]"
Object.prototype.toString.call({ a: 'hi' }); // "[object Object]"
Object.prototype.toString.call([1, 'a']); // "[object Array]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(() => {}); // "[object Function]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(Symbol(1)); // "[object Symbol]"