JS 类型判断:掌握 4 种方式,拒绝错误判断!
2024-01-19 00:04:23
在 JavaScript 中,变量类型判断是一个常见且重要的操作。准确判断变量类型可以帮助我们更好地理解代码逻辑,避免错误判断导致的程序问题。在本文中,我们将介绍四种 JS 类型判断的方法:typeof、typeof typeof、instanceof 和 Object.prototype.toString,帮助您掌握 JS 类型判断的技巧。
typeof:最常用的类型判断方法
typeof 是 JavaScript 中最常用的类型判断方法。它可以判断变量的原始类型,包括:
- string:字符串类型
- number:数字类型
- boolean:布尔类型
- undefined:未定义类型
- object:对象类型
- symbol:Symbol 类型(ES6 新增)
console.log(typeof 'hello'); // "string"
console.log(typeof 123); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"
console.log(typeof Symbol('foo')); // "symbol"
需要注意的是,typeof null 返回 "object",这是因为在 JavaScript 中,null 被认为是一个对象,而不是基本类型。
typeof typeof:判断变量是否为原始类型
typeof typeof 可以用来判断变量是否为原始类型。如果变量是原始类型,那么 typeof typeof 将返回 "string";如果变量是对象类型,那么 typeof typeof 将返回 "object"。
console.log(typeof typeof 'hello'); // "string"
console.log(typeof typeof 123); // "string"
console.log(typeof typeof true); // "string"
console.log(typeof typeof undefined); // "string"
console.log(typeof typeof null); // "object"
console.log(typeof typeof Symbol('foo')); // "object"
instanceof:判断变量是否属于某个类
instanceof 可以用来判断变量是否属于某个类。如果变量属于某个类,那么 instanceof 将返回 true;否则,instanceof 将返回 false。
class Person {
constructor(name) {
this.name = name;
}
}
const person = new Person('John');
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
console.log(person instanceof Array); // false
Object.prototype.toString:获取变量的构造函数名称
Object.prototype.toString 可以用来获取变量的构造函数名称。我们可以通过这个名称来判断变量的类型。
console.log(Object.prototype.toString.call('hello')); // "[object String]"
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
console.log(Object.prototype.toString.call(Symbol('foo'))); // "[object Symbol]"
需要注意的是,Object.prototype.toString.call() 方法返回的是一个字符串,我们需要通过正则表达式来提取构造函数名称。
const getType = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1);
};
console.log(getType('hello')); // "String"
console.log(getType(123)); // "Number"
console.log(getType(true)); // "Boolean"
console.log(getType(undefined)); // "Undefined"
console.log(getType(null)); // "Null"
console.log(getType(Symbol('foo'))); // "Symbol"
总结
在 JavaScript 中,类型判断是一个常见且重要的操作。本文介绍了四种 JS 类型判断的方法:typeof、typeof typeof、instanceof 和 Object.prototype.toString。通过这些方法,我们可以准确判断变量类型,避免错误判断导致的程序问题。