说说如何判断数据类型
# 是什么
数据类型:js 中变量的存储类型
- 基础: string number boolean null undefined symbol
- 引用: object(object array function)
# 判断方式
- typeof
- instanceof
- constructor
- Object.prototype.toString.call
# typeof
- 可以判断基础数据类型
- 判断引用类型都返回 object, 除了 function
typeof 1; // number
typeof {}; // object
typeof function() {}; // function
# instanceOf
根据原型链查找进行对比,返回布尔值
let a = new Number();
if (a instanceof Number) {
console.log("true");
}
原理
function myInstanceof(left, right) {
let leftProto = left.__proto__;
let rightPrototype = right.prototype;
while (true) {
if (leftProto === null || typeof leftProto !== "object") return false;
if (leftProto === rightPrototype) return true;
leftProto = leftProto.__proto__;
}
}
# construcor
function Foo() {}
let f = new Foo();
f.constructor === Foo;
# Object.prototype.toString
返回值:前面小写object, 后面大写类型
let a = 'fang'
Object.prototype.toString.call(a) // [object String]
Object.prototype.toString.call({}) // [object Object]
上次更新: 2021/12/19, 18:05:42