函数的arguments为什么不是数组?如何转化为数组?
因为arguments本身并不能调用数组方法,它是一个另外一种对象类型,只不过属性从0开始排,依次为0 1 2…最后还有callee和length属性,我们也把这样的对象成为类数组。
常见的类数组还有:
1.用getElementsByTagName/ClassName()获得的HTMLCollection
2.用querySelector获得的nodeList
那这就导致很多数组的方法就不能用了,必要时需要我们将它们转换为数组,有哪些方法呐?
1.Array.prototype.slice.call()
function sum(a,b){let args = Array.prototype.slice.call(arguments);console.log(args.reduce((sum,cur)=>sum+cur));//args可以调用数组原生的方法
}
sum(1,2);//
2.Array.from()
function sum(a,b){let args = Array.from(arguments);console.log(args.reduce((sum,cur)=>sum+cur));//args可以调用数组原生的方法
}
sum(1,2);//3
3.ES6展开运算符
function sum(a,b){let args = [...arguments];console.log(args.reduce((sum,cur)=>sum+cur));//args可以调用数组原生的方法
}
sum(1,2);//3
4.利用concat+apply
function sum(a,b){let args = Array.prototype.concat.apply([],arguments);//apply方法会把第二个参数展开console.log(args.reduce((sum,cur)=>sum+cur));//args可以调用数组原生的方法
}
sum(1,2);//3