function 中 arguments 是数组吗?如果不是如何转化为数组?
一. 什么是 arguments
agruments 是function中可以被直接访问的变量,在函数调用时才会有值,本质不是一个数组,是一个类数组。
function sum(a, b) {
console.log(arguments) // [Arguments] { '0': 1, '1': 2 }
}
sum(1, 2);
arguments本身并不能调用数组方法,它是一个另外一种对象类型,属性从0开始排,依次为0,1,2...最后还有callee和length属性。我们也把这样的对象称为类数组
二. arguments 属性
arguments 有两个属性 callee 和 length
function sum(a, b) {
console.log(arguments.callee) //[Function: sum]
console.log(arguments.length) //2
}
sum(1, 2);
-
callee:
arguments.callee属性包含当前正在执行的函数。 -
length
arguments.length函数入参长度
三. 如何转化为数组
1.Array.prototype.slice.call
function sum(a, b) {
console.log(Array.prototype.slice.call(arguments)) // [1,2]
}
sum(1, 2);
2. Array.from
function sum(a, b) {
console.log(Array.from(arguments)) // [1,2]
}
sum(1, 2);
3. ES6展开运算符
function sum(a, b) {
console.log([...arguments]) // [1,2]
}
sum(1, 2);
通过以上方法将 arguments 转化为数组即可使用数组的方法了。