前端面试题-如何区分数组和对象

以下为前端区分对象和数组的方法:

1、es6的Array.isArray()

Array.isArray([]) // true
Array.isArray()   // false

2、操作符instanceof

const obj = {}
obj instanceof Array //false

const arr = []
arr instanceof Array //true

[] instanceof Array //true
{} instanceof Array //Uncaught SyntaxError
// 报错原因是{} 不仅是空对象,同时也是空代码块;js的优先级会先识别是空代码块,所以就报错了
//修改以下则是空对象
({}) instanceof Array //false

3、Object.prototype.toString.call()

Object.prototype.toString().call({}) // [Object Object] 
Object.prototype.toString().call([]) // [Object Array] 
//返回的是字符串类型可以直接做判断

问:为什么使用call?

答:改变this指向;Object.prototype.toString() 打印出来的是[Object Object] ,因为在原型链上,Object是对象,我们怎么用来判断我们的类型呢?使用call改变指向,让toString我们传进去的类型,所以Object.prototype.toString().call([])就是打印的是[Object Array],而不是原始的Object

4、 使用constructor构造函数

const arr = []
arr.constructor.toString() //'function Array() { [native code] }'

const arr = {}
arr.constructor.toString() //'function Object() { [native code] }'
//可以使用 indexOf('类型') > -1 判断是否是对象

{}.constructor.toString()y //Uncaught SyntaxError
// 报错原因是{} 不仅是空对象,同时也是空代码块;js的优先级会先识别是空代码块,所以就报错了

5、Array.prototype.isPrototypeOf()   使用isPrototypeOf判断是否在选型上

Array.prototype.isPrototypeOf([]) // true
Array.prototype.isPrototypeOf({}) // false

值得注意的是Object.prototype.isPrototypeOf([]) 打印出来的也是true

typeof([])类型是object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喂!大掌柜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值