1.什么是argument
argument是一个类数组对象,控制台打印出来的是一个数组,但并不是真正的数组,所以说arguments 是一个类数组的对象,我们叫他伪数组。
2. argument 操作
arguments 是个类数组对象,其包含一个 length 属性,可以用 arguments.length 来获得传入函数的参数个数。
function func() {
console.log("The number of parameters is " + arguments.length);
}
func();
func(1, 2);
func(1, 2, 3);
执行结果如下:
The number of parameters is 0
The number of parameters is 2
The number of parameters is 3
3.arguments 转数组
通常使用下面的方法来将 arguments 转换成数组:
Array.prototype.slice.call(arguments);
还有一个更简短的写法:
[ ].slice.call(arguments);
在这里,只是简单地调用了空数组的 slice 方法,而没有从 Array 的原型层面调用。
问:为什么上面两种方法可以转换呢?
首先,slice 方法得到的结果是一个数组,参数便是 arguments。事实上,满足一定条件的对象都能被 slice 方法转换成数组。看个例子:
const obj = { 0: "A", 1: "B", length: 2 };
const result = [].slice.call(obj);
console.log(Array.isArray(result), result); //true ["A", "B"]
从上面例子可以看出,条件就是:
1) 属性为 0,1,2…;
2) 具有 length 属性;