typeof"object"。"undefined":表示值未定义。"boolean":表示布尔值。"number":表示数字。"bigint":表示大整数(ES2020)。"string":表示字符串。"symbol":表示符号(ES6)。"function":表示函数。"object":表示对象(包括数组、null等)。console.log(typeof 42); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 10n); // "bigint"
console.log(typeof function() {}); // "function"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof null); // "object" // null 是特殊情况
instanceofprototype。true 或 false。function Person() {}
let alice = new Person();
console.log(alice instanceof Person); // true
console.log(alice instanceof Object); // true
let arr = [];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
检测范围:
typeof:可以用于检测所有原始类型和函数,但对于对象类型返回 "object",无法进一步区分具体类型。instanceof:只能用于检测对象类型,检查对象是否是某个构造函数的实例。返回类型:
typeof:返回一个表示类型的字符串。instanceof:返回一个布尔值。具体用途:
typeof:适用于简单类型检查,尤其是原始类型(如数字、字符串、布尔值等)。instanceof:适用于对象类型检查,尤其是在需要判断对象是否是某个类或构造函数的实例时。typeof 使用场景:
let value;
if (typeof value === 'undefined') {
console.log('value is undefined');
}
if (typeof value === 'number') {
console.log('value is a number');
}
if (typeof value === 'function') {
console.log('value is a function');
}
instanceof 使用场景:
class Animal {}
class Dog extends Animal {}
let myDog = new Dog();
if (myDog instanceof Dog) {
console.log('myDog is an instance of Dog');
}
if (myDog instanceof Animal) {
console.log('myDog is an instance of Animal');
}
if (myDog instanceof Object) {
console.log('myDog is an instance of Object');
}
typeof:适用于检查原始类型、函数类型等,返回类型字符串。对于对象类型,只能返回 "object",无法区分具体对象类型。instanceof:适用于检查对象类型和继承关系,返回布尔值。只能用于对象,不适用于原始类型。理解 typeof 和 instanceof 的区别和使用场景,可以更好地进行类型检查和调试,提高代码的健壮性和可维护性。