JavaScript 检测数据类型的几种方式
JavaScript 检测数据类型的几种方式
typeof
typeof
是 JavaScript 中的一个操作符,可以用来检测数据类型,使用方式如下:
typeof operand
typeof(operand)
typeof
始终会返回一个字符串,下表总结了所有可能返回的值:
数据类型 | 返回值 |
---|---|
String | "string" |
Number | "number" |
Boolean | "boolean" |
Symbol | "symbol" |
BigInt | "bigint" |
Null | "object" |
Undefined | "undefined" |
Function | "function" |
Object | "object" |
注意:严格意义上来说,函数在 ECMAScript 中被认为是对象,并不是一种数据类型。
从上表可以看出,使用 typeof
并不能完美的检测 JavaScript 中的数据类型,对于 Null
和 Object
都会返回 "object"
,这是因为特殊值 null
被认为是一个对空对象的引用。如果预期被检测的值是基本类型的话,可以使用此方法。
instanceof
instanceof
是 JavaScript 中的一个运算符,用于检查一个对象是否属于某个特定的 class
,也就是类检查。它始终返回一个布尔值。
object instanceof Class
举例说明:
// ES5
function Person() {}
new Person() instanceof Person // true
// ES6
class Person {}
const man = new Person()
man instanceof Person // true
我们可以创建一个构造函数或者类 Person
,并且生成一个实例 man
,通用 instanceof
操作符就可以知道 man
属于 Person
。
还可以通过 JavaScript 内置标准库来举例:
const arr = [1, 2, 3]
arr instanceof Array // true
arr instanceof Object // true
上述情况中,arr
即属于 Array
也属于 Object
,这是因为 Array
继承自 Object
。
constructor
constructor
是一种用于创建和初始化 class
创建的对象的特殊方法,可以用来检测数据类型。
function Person() {}
Person.prototype.constructor === Person // true
相比于 instanceof
,constructor
可以检测基本数据类型:
const num = 123
num.constructor === Number // true
const str = 'name'
str.constructor === String // true
const symbol = Symbol()
symbol.constructor === Symbol // true
对于
instanceof
和constructor
来说,都有一个缺点就是只要是原型被修改了,那么检测方法就不准确了。
function Person() {}
Person.prototype = Array.prototype
const man = new Person()
man instanceof Array // true
man instanceof Function // false
Number.prototype.constructor = 'name'
const num = 1
num.constructor === Number // false
Object.prototype.toString.call()
利用 Object.prototype.toString
返回对象所属类的信息。因为 toString
不接受参数,可以通过改变 toString
中 this
指向来返回指定参数的类型。
Object.prototype.toString.call(value) === "[object Type]"
下面表格展示了常见的类型:
类型 | 返回值 |
---|---|
Object.prototype.toString.call("name") |
"[object String]" |
Object.prototype.toString.call(123) |
"[object Number]" |
Object.prototype.toString.call(true) |
"[object Boolean]" |
Object.prototype.toString.call(Symbol()) |
"[object Symbol]" |
Object.prototype.toString.call(123n) |
"[object BigInt]" |
Object.prototype.toString.call(null) |
"[object Null]" |
Object.prototype.toString.call(undefined) |
"[object Undefined]" |
Object.prototype.toString.call({}) |
"[object Object]" |
Object.prototype.toString.call([]) |
"[object Array]" |
Object.prototype.toString.call(function(){}) |
"[object Function]" |
Object.prototype.toString.call(new Date()) |
"[object Date]" |
Object.prototype.toString.call(new RegExp()) |
"[object RegExp]" |
Object.prototype.toString.call(new Set()) |
"[object Set]" |
Object.prototype.toString.call(new Map()) |
"[object Map]" |
Object.prototype.toString.call(new Error()) |
"[object Error]" |