JavaScript中,arguments是一种特殊类型的内置变量,它可以处理函数中任意数量的参数。
考虑一个场景,函数定义不接受任何参数,但在运行时,调用者想要传递一些参数,arguments就派上用场了。
arguments变量既类似于数组又可迭代,但它不是数组。此外,它不支持数组方法,因此我们不能调用arguments.map(…)等。
function show(){
console.log(arguments[0] + " " + arguments[1]); // hello world
}
show("hello","world");如果参数过多,还想明示参数,则使用如下写法:
function show(...args){
console.log(args[0] + " " + args[1]); // hello world
}
show("hello","world");或者单独明示部分参数:
function show(a, ...args){
console.log(a, args[0] + " "); // hello world
}
show("hello","world");