一、typeOf
只能判断基本数据类型。检测不了object,null和 Array,检测哪个都会返回object
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 [1, 2, 3]); // 输出: "object"
console.log(typeof { name: 'Alice', age: 30 }); // 输出: "object"
console.log(typeof function() {}); // 输出: "function"
二、constructor
语法:数据结构.constructor
返回值:该数据结构所属的构造函数
缺点:undefined和null检测不了
console.log((42).constructor === Number); // 输出: true
console.log('Hello'.constructor === String); // 输出: true
console.log(true.constructor === Boolean); // 输出: true
console.log(undefined.constructor === undefined); // 输出: true
console.log(null.constructor === Object); // 输出: true
console.log([1, 2, 3].constructor === Array); // 输出: true
console.log({ name: 'Alice', age: 30 }.constructor === Object); // 输出: true
console.log((function() {}).constructor === Function); // 输出: true
三、instanceOf
语法:数据结构.instanceOf 构造函数
意义:该数据是不是构造函数的实例对象
返回值:true/false
缺点:undefined和null检测不了
console.log(42 instanceof Number); // 输出: false
console.log('Hello' instanceof String); // 输出: false
console.log(true instanceof Boolean); // 输出: false
console.log(undefined instanceof undefined); // 输出: false
console.log(null instanceof Object); // 输出: false
console.log([1, 2, 3] instanceof Array); // 输出: true
console.log({ name: 'Alice', age: 30 } instanceof Object); // 输出: true
console.log((function() {}) instanceof Function); // 输出: true
// 自定义类的示例
class Person {
constructor(name) {
this.name = name;
}
}
const person = new Person('Alice');
console.log(person instanceof Person); // 输出: true
console.log(person instanceof Object); // 输出: true
四、Object.prototype.toString.call()(数据结构)
返回值:‘[object 数据类型]'
优点:可以准确判断所有数据类型
注意:该方法中的call也可以是apply和bind,用bind时需要在末尾加()表示立即执行
举例:
1.检测基本数据类型
const num = 42;
console.log(Object.prototype.toString.call(num)); // 输出: "[object Number]"
const str = "Hello";
console.log(Object.prototype.toString.call(str)); // 输出: "[object String]"
const bool = true;
console.log(Object.prototype.toString.call(bool)); // 输出: "[object Boolean]"
const undef = undefined;
console.log(Object.prototype.toString.call(undef)); // 输出: "[object Undefined]"
const nul = null;
console.log(Object.prototype.toString.call(nul)); // 输出: "[object Null]"
2.检测对象类型
const obj = { name: "John", age: 30 };
console.log(Object.prototype.toString.call(obj)); // 输出: "[object Object]"
const arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr)); // 输出: "[object Array]"
const date = new Date();
console.log(Object.prototype.toString.call(date)); // 输出: "[object Date]"
3.检测自定义类型
class Person {
constructor(name) {
this.name = name;
}
}
const person = new Person("John");
console.log(Object.prototype.toString.call(person)); // 输出: "[object Object]"
以上就是四种数据检测方法之间的比较