数据类型的检测方式

... 2025-7-10 JavaScript
  • 数据类型
大约 2 分钟

# typeof

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

typeof '' // 'string'
typeof 1 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof function () {} // 'function'
typeof BigInt(1) // 'bigint'
typeof Symbol('1') // 'symbol'
1
2
3
4
5
6
7
8
9
10

# instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

用来判定某一个对象是否是某一个构造函数的实例。

但是 instanceof 会有一个问题, 它的问题在于假定只有一个全局执行的环境。

如果网页中包含多个框架,那实际上就存在 两个以上不同的全局执行环境, 从而存在两个以上不同版本的 Array 构造函数。

如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有不同的构造函数。

语法:object instanceof constructor

'1' instanceof String // false
new String('1') instanceof String // true

1 instanceof Number // false
new Number(1) instanceof Number // true

true instanceof Boolean // false
new Boolean(true) instanceof Boolean // true

;[] instanceof Array //true
;({} instanceof Object) //true
;(function () {} instanceof Function) //true
1
2
3
4
5
6
7
8
9
10
11
12

# constructor

根据对象的 constructor 判断

Object 的每个实例都有构造函数 constructor,用于保存着用于创建当前对象的函数。

但是如果手动更改了对象的原型,那么 constructor 会指向更改后的原型

'1'.constructor === String // true
(1).constructor === Number // true
true.constructor === Boolean // true

[].constructor === Array // true
(function () {}).constructor === Function // true
({}).constructor === Object // true

// (null).constructor === Null // 报错:无法读取null的属性
// (undefined).constructor === Undefined // 报错:无法读取undefined的属性
1
2
3
4
5
6
7
8
9
10

# Object.prototype.toString.call()

  • Object.prototype.toString() 的调用

    对于 Object.prototype.toString() 方法,会返回一个形如 "[object XXX]" 的字符串。

    如果对象的 toString() 方法未被重写,就会返回如上面形式的字符串。

    但是,大多数对象的 toString() 方法都是重写了的,这时,需要用 call() 或 Reflect.apply() 等方法来调用。

let _toString = Object.prototype.toString
_toString.call(1) // '[object Number]'
_toString.call('1') // '[object String]'
_toString.call(true) // '[object Boolean]'
_toString.call([]) // '[object Array]'
_toString.call({}) // '[object Object]'
_toString.call(function () {}) //
_toString.call(null) // '[object Function]'
_toString.call(undefined) // '[object Undefined]'
_toString.call(/d+/) // '[object RegExp]'
_toString.call(new Date()) // '[object Date]'
_toString.call(new Error()) // '[object Error]'

_toString.call(
  (function () {
    return arguments
  })() // '[object Arguments]'
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次编辑于: 2025年7月10日 04:01
贡献者: HugStars