js 中判断对象的方法
2025年6月25日大约 2 分钟
js 中判断对象的方法
typeof
typeof 运算符返回一个字符串,表示操作数的类型。
typeof 会返回以下几种结果:
- undefind
- boolean
- number
- bigint
- string
- symbol
- function
- object
使用 typeof 判断一个变量是否是对象的时候需要注意的是
typeof null === 'object' //成立
这个原因是 js 语言底层设计的缺陷,在底层存储变量时使用的是二进制,使用标志为 0 表示一个变量为,null 在存储时表示为 0x00,全部为 0,但 null 并不是一个对象,在 js 中,null 是一种基本类型,表示空指针。
除此之外,其他任对象使用 typeof 都会返回 “object”
Object.prototype.toString
使用 Object.prototype.toString 方法判断一个变量是否是对象,这种方式判断的更为准确
名称 | typeof | Object.prototype.toString |
---|---|---|
Undefined | undefined | [object Undefined] |
Null | object | [object Null] |
Boolean | boolean | [object Boolean] |
Number | number | [object Number] |
String | string | [object String] |
Symbol | symbol | [object Symbol] |
BigInt | bigint | [object BigInt] |
Object | object | [object Object] |
Array | object | [object Array] |
Function | function | [object Function] |
ArrowFunction | function | [object Function] |
Date | object | [object Date] |
RegExp | object | [object RegExp] |
Error | object | [object Error] |
Map | object | [object Map] |
Set | object | [object Set] |
WeakMap | object | [object WeakMap] |
WeakSet | object | [object WeakSet] |
Promise | object | [object Promise] |
Int8Array | object | [object Int8Array] |
Uint8Array | object | [object Uint8Array] |
Uint8ClampedArray | object | [object Uint8ClampedArray] |
Float32Array | object | [object Float32Array] |
Float64Array | object | [object Float64Array] |
Math | object | [object Math] |
JSON | object | [object JSON] |
Arguments | object | [object Arguments] |
但是这种方法并不是一种安全的方法
Object.prototype.toString() 返回的是一个变量的描述,
在 js 中使用Symbol.toStringTag
,他并不是一个底层属性,
在 js 代码中是可以访问的,也就是说可以被篡改的
const a = {
value: 1,
[Symbol.toStringTag]: 'Number',
}
Object.prototype.toString.call(a) // 这里会返回 '[object Number]'
instanceof
instanceof 不能准确判断一个变量是不是对象本身,它判断的是:变量是否是某个构造函数的实例(即:构造函数的 prototype 是否在其原型链上)。
对于原始类型对原始类型返回 false,对象返回 true
但是这种方法也是不安全的,会遭到原型链污染
//原型链污染
function likeArray() {}
likeArray.prototype = Object.create(Array.prototype)
const obj2 = new likeArray()
console.log(obj2 instanceof Array) // true
constructor
构造函数和 instanceof 类似,可以被篡改
Array.isArray()
目前最准确的和安全的判断一个变量是否是数组的方法,无法篡改