JavaScript类型检测:typeof、instanceof、Object.prototype.toString.call区别
1.typeof
官方文档说明:typeof 操作符返回一个字符串,表示未经计算的操作数的类型。
用法:
// 数值
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 尽管它是 "Not-A-Number" (非数值) 的缩写
typeof Number(1) === 'number'; // Number 会尝试把参数解析成数值
typeof 42n === 'bigint';
// 字符串
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // 注意内容为数字的字符串仍是字符串
typeof (typeof 1) === 'string'; // typeof 总是返回一个字符串
typeof String(1) === 'string'; // String 将任意值转换为字符串,比 toString 更安全
// 布尔值
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean() 会基于参数是真值还是虚值进行转换
typeof !!(1) === 'boolean'; // 两次调用 ! (逻辑非) 操作符相当于 Boolean()
// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';
// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
// 对象
typeof {a: 1} === 'object';
// 使用 Array.isArray 或者 Object.prototype.toString.call
// 区分数组和普通对象
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object'; // 历史结果请参阅正则表达式部分
// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
// 函数
typeof function() {} === 'function';
typeof class C {} === 'function'
typeof Math.sin === 'function';
下表总结了 typeof 可能的返回值。

typeof对于基础类型(Undefined,Null,Boolean,Number,String,BigInt,Symbol)除了null以外都可以显示正确的类型,对于数组和对象都会显示object,对于函数会显示function。对数组,对象,时间戳,null等类型返回的都是object类型,不能准确的定位其类型。对于数组、对象、时间戳、我们可以采用instance of 来进行判断。
2.instanceof
官方文档说明:instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。它的原理是根据原型链来查找。
举例子:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
👆的例子表明 构造函数 Car的 prototype 属性是在实例对象 auto 的原型链上注意:instanceof可以判断数据类型,但是其类型是基于对象Object的(可以简记为typeof判断为Object)。有没有更好的判断变量类型的方法?有的 可以使用Object.prototype.toString.call(var),可以更加准确的判断某个变量的类型。
3.Object.prototype.toString.call
Object.prototype.toString.call()是在Object.prototype.toString()方法之上来实现的,使其可以判断各种数据类型每个对象都有一个toString()方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString()方法被每个Object对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中type是对象的类型。对于toString还有一些有趣的东西 ,大佬这篇文章讲的不错,一起学习。
浅谈Object.prototype.toString.call(obj)功能及原理
唉,我太懒了!


浙公网安备 33010602011771号