数据类型检测的方式有哪些

50 阅读2分钟

数据类型检测的方式

1. typeof

typeof 操作符可以返回一个表示数据类型的字符串。不过,数组、对象、null 都会被判断为 object,对于其他类型的判断则是正确的。

示例代码

console.log(typeof undefined); // 'undefined'
console.log(typeof true); // 'boolean'
console.log(typeof 123); // 'number'
console.log(typeof 'hello'); // 'string'
console.log(typeof Symbol()); // 'symbol'
console.log(typeof 123n); // 'bigint'
console.log(typeof []); // 'object'
console.log(typeof {}); // 'object'
console.log(typeof null); // 'object'
console.log(typeof function() {}); // 'function'

2. instanceof

instanceof 可以正确判断对象的类型,其内部运行机制是判断在对象的原型链中能否找到该类型的原型。需要注意的是,instanceof 只能正确判断引用数据类型,而不能判断基本数据类型。instanceof 运算符可以用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。

示例代码

const arr = [];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true

const num = 123;
console.log(num instanceof Number); // false

function Person() {}
const person = new Person();
console.log(person instanceof Person); // true

3. constructor

constructor 有两个作用,一是判断数据的类型,二是对象实例通过 constructor 对象访问它的构造函数。不过,如果创建一个对象并改变它的原型,constructor 就不能用来准确判断数据类型了。

示例代码

const arr = [];
console.log(arr.constructor === Array); // true

const num = 123;
console.log(num.constructor === Number); // true

function Person() {}
const person = new Person();
console.log(person.constructor === Person); // true

// 改变原型后,constructor 判断不准确
const obj = {};
Object.setPrototypeOf(obj, Array.prototype);
console.log(obj.constructor === Array); // true,但 obj 并非真正的数组

4. Object.prototype.toString.call()

Object.prototype.toString.call() 使用 Object 对象的原型方法 toString 来判断数据类型。不同的对象类型调用 obj.toString() 时,由于原型链的原因,调用的是重写之后的 toString 方法,而不会调用 Object 原型上的 toString 方法(返回对象的具体类型)。因此,在想要得到对象的具体类型时,应该调用 Object 原型上的 toString 方法。

示例代码

const arr = [];
console.log(Object.prototype.toString.call(arr)); // '[object Array]'

const num = 123;
console.log(Object.prototype.toString.call(num)); // '[object Number]'

const str = 'hello';
console.log(Object.prototype.toString.call(str)); // '[object String]'

const obj = {};
console.log(Object.prototype.toString.call(obj)); // '[object Object]'

const func = function() {};
console.log(Object.prototype.toString.call(func)); // '[object Function]'

const nullValue = null;
console.log(Object.prototype.toString.call(nullValue)); // '[object Null]'

const undefinedValue = undefined;
console.log(Object.prototype.toString.call(undefinedValue)); // '[object Undefined]'

综上所述,不同的数据类型检测方式各有优缺点,在实际开发中需要根据具体需求选择合适的方法。