对数据类型进行检测的方式有多种,常用的方法包括 typeof
、instanceof
、constructor
和 Object.prototype.toString.call()
。
目录
1. typeof
typeof
操作符返回一个字符串,表示未经计算的操作数的类型。适用于基本数据类型的检测。
语法
typeof operand
示例
console.log(typeof 42); // 输出: "number"
console.log(typeof 'hello'); // 输出: "string"
console.log(typeof true); // 输出: "boolean"
console.log(typeof undefined); // 输出: "undefined"
console.log(typeof null); // 输出: "object" (这是个历史遗留问题)
console.log(typeof {}); // 输出: "object"
console.log(typeof []); // 输出: "object"
console.log(typeof function(){}); // 输出: "function"
2. instanceof
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。适用于检测对象的具体类型。
语法
object instanceof constructor
示例
console.log([] instanceof Array); // 输出: true
console.log([] instanceof Object); // 输出: true
console.log(function(){} instanceof Function); // 输出: true
console.log({} instanceof Object); // 输出: true
function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(person instanceof Person); // 输出: true
console.log(person instanceof Object); // 输出: true
3. constructor
每个对象都有一个 constructor
属性,指向用于创建该对象的构造函数。
示例
console.log((42).constructor === Number); // 输出: true
console.log(('hello').constructor === String); // 输出: true
console.log((true).constructor === Boolean); // 输出: true
console.log(({}).constructor === Object); // 输出: true
console.log(([]).constructor === Array); // 输出: true
console.log((function(){}).constructor === Function); // 输出: true
function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(person.constructor === Person); // 输出: true
4. Object.prototype.toString.call()
Object.prototype.toString.call()
方法返回一个表示对象类型的字符串。适用于准确检测对象的类型,包括内置对象和自定义对象。
语法
Object.prototype.toString.call(value)
示例
console.log(Object.prototype.toString.call(42)); // 输出: "[object Number]"
console.log(Object.prototype.toString.call('hello')); // 输出: "[object String]"
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({})); // 输出: "[object Object]"
console.log(Object.prototype.toString.call([])); // 输出: "[object Array]"
console.log(Object.prototype.toString.call(function(){})); // 输出: "[object Function]"
function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(Object.prototype.toString.call(person)); // 输出: "[object Object]"
小结
typeof
适用于检测基本数据类型,但对null
和复杂类型(如数组)存在局限性。instanceof
适用于检测对象的具体类型,尤其是自定义对象类型。constructor
可以用于检测对象是由哪个构造函数创建的,但对于原型链被修改的对象可能不准确。Object.prototype.toString.call()
是一种更通用且准确的方法,适用于检测所有类型的数据。