page contents

为什么函数的 arguments 参数是类数组而不是数组 如何遍历类数组?

轩辕小不懂 发布于 2021-12-18 11:05
阅读 574
收藏 0
分类:WEB前端开发
2685
Nen
Nen
- 程序员

arguments是一个对象,它的属性是从 0 开始依次递增的数字,还有callee和length等属性,与数

forEach, reduce等,所以叫它们类数组。

要遍历类数组,有三个方法:

(1)将数组的方法应用到类数组上,这时候就可以使用call和apply方法,如

function foo(){

 Array.prototype.forEach.call(arguments, a => console.log(a))

}


2)使用Array.from方法将类数组转化成数组:
function foo(){
 const arrArgs = Array.from(arguments)
 arrArgs.forEach(a => console.log(a))
}

(3)使用展开运算符将类数组转化成数组
function foo(){
 const arrArgs = [...arguments]
 arrArgs.forEach(a => console.log(a))
}

请先 登录 后评论