- 定义:
arguments
是一个对应于传递给函数的参数的类数组对象。 arguments
对象不是一个Array
。它类似于Array
,但除了length属性和索引元素之外没有任何Array
属性。
arguments
没有 pop 方法。但是它可以被转换为一个真正的Array
:
//第一种方法
function sortNumber(){
return Array.prototype.slice.call(arguments).sort();
}
//第二种方法
const args = Array.from(arguments);
const args = [...arguments];
如果调用的参数多于正式声明接受的参数,则可以使用arguments
对象。使用 arguments.length
来确定传递给函数参数的个数,然后使用arguments
对象来处理每个参数。
typeof参数返回 'object'。
console.log(typeof arguments); // 'undefined'
// arguments 对象只能在函数内使用
function test(a){
console.log(a,Object.prototype.toString.call(arguments));
console.log(arguments[0],arguments[1]);
console.log(typeof arguments[0]);
}
test(1);
/*
1 "[object Arguments]"
1 undefined
number
*/
遍历求和
function add() {
var sum =0,
len = arguments.length;
for(var i=0; i<len; i++){
sum += arguments[i];
}
return sum;
}
add() // 0
add(1) // 1
add(1,2,3,4); // 10