一、arguments 是什么?
JavaScript 中每个函数内都能访问一个特殊变量 arguments,这个变量维护着所有传递到这个函数中的参数列表。
二、arguments 是什么类型?
arguments 变量不是一个数组(Array),只是长的很像数组(Array-like)。尽管在语法上它有数组相关的属性 length, 但它不会从 Array.prototype 继承属性,实际上它是一个对象(Object)。
因此,无法对 arguments 变量使用标准的数组方法,比如 push/pop/shift/unshift等 。 虽然使用 for 循环遍历也是可以的,但是为了更好的使用数组方法,最好把它转化为一个真正的数组。
// 检测arguments的类型
typeof arguments // object
Object.prototype.toString.call(arguments) // [object Arguments]
三、如何转换?
把 arguments 转换成 数组,可以通过以下方法:
// ES5
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
// ES6
const args = Array.from(arguments);
const args = [...arguments];