在 JavaScript 中,有多种方法可以用来判断数据类型。
typeof 操作符
typeof 操作符用于返回一个字符串,表示未经计算的操作数的数据类型。
| 类型 | typeof 返回值 |
|---|---|
| Null | "object" |
| Undefined | "undefined" |
| Boolean | "boolean" |
| Number | "number" |
| BigInt | "bigint" |
| String | "string" |
| Symbol | "symbol" |
| Function 对象 | "function" |
| 其他任何对象 | "object" |
typeof null 虽然返回 object,但是这不代表 null 就是对象,这其实是 JavaScript 的一个 Bug,且从 JavaScript 诞生以来便如此。
类也是函数。
instanceof 操作符
instanceof 操作符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
console.log([] instanceof Array); // 输出 true
console.log([] instanceof Object); // 输出 true
console.log({} instanceof Object); // 输出 true
console.log(function() {} instanceof Function); // 输出 true
Object.prototype.toString.call()
Object.prototype.toString.call() 方法可以返回一个表示对象类型的字符串,通常用于更精确地判断数据类型。
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({ name: 'John' })); // 输出 "[object Object]"
console.log(Object.prototype.toString.call([1, 2, 3])); // 输出 "[object Array]"
console.log(Object.prototype.toString.call(function() {})); // 输出 "[object Function]"
console.log(Object.prototype.toString.call(new Date())); // 输出 "[object Date]"
console.log(Object.prototype.toString.call(/regex/)); // 输出 "[object RegExp]"
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
参考
typeof
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof