JS如何区分Object与Array
“在项目中我们会遇到,怎样去区分对象和数组的问题,然后对应不同的数据去执行不同的业务,那你们有没有因为这个问题踩过坑呢?
”
区分的方法
typeof
相信大家都用过typeof,我们判断类型经常会使用typeof,但你会发现,在这次讨论的话题中,它就没有那么香了
例如:
const arr = [1, 2, 3]
const obj = {name: 'zhangsan'}
console.log(typeof arr) // object
console.log(obj) // object
那这是为什么呢?
因为typeof返回的类型只有
| 类型 | 结果 |
|---|---|
| Undefined | "undefined" |
| Null | "object" |
| Boolean | "boolean" |
| Number | "number" |
| BigInt | "bigint" |
| String | "string" |
| Symbol | "symbol" |
| 宿主对象 | 取决于具体实现 |
| Function 对象 | "function" |
| 其他任何对象 | "object" |
在表中可以看出,Array 是归为其他任何对象了 所以 typeof [] 的结果为 'object'
“既然出了问题,那我们怎么来解决呢?官方给出了两种解决方案,使用
”Array.isArray或者Object.prototype.toString.call
官方推荐的
Array.isArray
const arr = [1,2,3]
const obj = {name: 'zhangsan'}
Array.isArray(arr) // true
Array.isArray(obj) // false
Object.prototype.toString.call
const arr = [1,2,3]
const obj = {name: 'zhangsan'}
Object.prototype.toString.call(obj)==="[object Array]" // false
Object.prototype.toString.call(arr)==="[object Array]" // true
其它的方法
instanceof
这个方法 左侧是待测对象 ,右侧是父构造函数
例如:
const arr = [1,2,3]
const obj = {name: 'zhangsan'}
arr instanceof Array // true
obj instanceof Array // false
isPrototypeOf()
const arr = [1,2,3]
const obj = {name: "zhangsan"}
Array.prototype.isPrototypeOf(arr) // true
Array.prototype.isPrototypeOf(obj) // false
构造函数constructor
const arr = [1,2,3]
const obj = {name: 'zhangsan'}
arr.constructor === Array
obj.constructor === Object
“总结:这几种判断类型除了typeof外,其它都可以判断出一个数据是对象还是数组,所以没有好坏之分。自己喜欢就好!
”
本文使用 mdnice 排版