数据类型检测
-
typeof
常用于检测基本数据类型
- 不能区分 null 和引用数据类型
typeof 'hello'; // string typeof('hello'); // string // 注意 typeof null; // object typeof []; // object typeof {}; // object
-
instanceof
常用于检测引用数据类型(特别是自定义类型)
- 不能用于检测基本数据类型字面量
- 原型链上的父类都会使得 instanceof 为 true
let o = {}; o instanceof Object; // true let arr = []; arr instanceof Array; // true // 注意 1 instanceof Number; // false
-
构造函数法
let arr = []; arr.constructor === Array; // true
-
使用最原始
toString()
方法(返回[object type]
)判断数据类型常用于检测内置对象
// Object.prototype.toString.call() // 基本数据类型 Object.prototype.toString.call(null); // [object Null] Object.prototype.toString.call(undefined); // [object Undefined] Object.prototype.toString.call(1); // [object Number] Object.prototype.toString.call(false); // [object Boolean] Object.prototype.toString.call('string'); // [object String] Object.prototype.toString.call(Symbol('symbol')); // [object Symbol] // 内部引用数据类型 Object.prototype.toString.call([1,2,3]); // [object Array] Object.prototype.toString.call(() => {}); // [object Function] Object.prototype.toString.call(new Date()); // [object Date] Object.prototype.toString.call(new RegExp()); // [object RegExp] // 自定义引用数据类型 function Persion(_name='name', _age=18){ this.name = _name; this.age = _age; } Object.prototype.toString.call(new Persion('girl')); // [object Object]