typeof
和 instanceof
都是 JavaScript 中用于检测数据类型的运算符,但它们的用途和实现方式不同。
typeof
运算符返回一个字符串,表示一个值的数据类型。它可以用于检测基本类型(如字符串、数字、布尔值、undefined、null、Symbol)和对象类型。例如:
typeof 'hello'; // 'string'
typeof 123; // 'number'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof null; // 'object'
typeof Symbol(); // 'symbol'
typeof {}; // 'object'
typeof []; // 'object'
typeof function() {}; // 'function'
需要注意的是,typeof null
返回的是 "object"
,这是一个历史遗留问题。
实际上,null
的类型应该是 null
,而不是 "object"
。这是因为 null
表示一个空值或者不存在的对象,而不是一个实际的对象。
需要注意的是,虽然 typeof null
返回 "object"
,但是 null
与其他对象类型是不同的,它没有任何属性和方法。因此,当我们需要检测一个变量是否为 null
时,最好使用全等运算符 ===
,例如:
let myVariable = null;if (myVariable === null) {console.log('myVariable is null');
}
instanceof
运算符用于检测一个对象是否是某个类(或其子类)的实例。它的语法为 object instanceof class
,其中 object
是要检测的对象,class
是要检测的类。例如:
const obj = {};
obj instanceof Object; // trueconst arr = [];
arr instanceof Object; // true
arr instanceof Array; // trueconst func = function() {};
func instanceof Object; // true
func instanceof Function; // true
需要注意的是,instanceof
运算符只能检测对象是否是某个类的实例,不能用于检测基本类型的数据。
综上所述,typeof
用于检测数据类型,instanceof
用于检测对象的类别。