arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。例如,如果一个函数传递了三个参数,你可以以如下方式引用他们:
arguments[0]
arguments[1]
arguments[2]
例如:
function howManyArgs() {
console.log(arguments.length);
}
howManyArgs("string", 45);//2
howManyArgs();//0
howManyArgs(12);//1
arguments对象不是一个 Array 。它类似于Array,但除了length属性和索引元素之外没有任何Array属性。例如,它没有 pop 方法。但是它可以被转换为一个真正的Array:
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
// ES2015
const args = Array.from(arguments);
对参数使用 typeof
console.log(typeof arguments); // 'object'
// 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
*/
您还可以使用Array.from()方法或扩展运算符将参数转换为真实数组:
var args = Array.from(arguments);
var args = [...arguments];
转载于:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments