1、概念
arguments 是一个对应于传递给函数的参数的类数组对象。
arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。
2、使用
arguments
对象不是一个 Array
。它类似于Array
,但除了length属性和索引元素之外没有任何Array
属性。
function demo(a){
console.log(arguments[0]);
}
demo(); //undefined
demo(1); //1
arguments
对象可以转换为数组
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
// ES2015
const args = Array.from(arguments); //使用Array.from()方法
const args = [...arguments]; //使用扩展运算符
3、属性
arguments.callee 指向当前执行的函数。
arguments.caller (已废弃)指向调用当前函数的函数。
arguments.length 指向传递给当前函数的参数数量。
arguments[@@iterator] 返回一个新的Array迭代器对象,该对象包含参数中每个索引的值。
4、剩余参数、默认参数和解构赋值参数
严格模式下,剩余参数、默认参数和解构赋值参数的存在不会改变 arguments对象的行为
'use strict' //使用严格模式
function func(a) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
func(10); // 10
function func(a) {
a = 99; // updating arguments[0] does not also update a
console.log(a);
}
func(10); // 10
function func(a =50) {
arguments[0] = 99;
console.log(a);
}
func(10); // 10
非严格模式中的函数没有包含剩余参数、默认参数和解构赋值参数,那么arguments
对象中的值会跟踪参数的值,同样参数的值也会跟踪arguments
对象中的值
function func(a) {
arguments[0] = 99; // 更新了arguments[0] 同样更新了a
console.log(a);
}
func(10); // 99
并且
function func(a) {
a = 99; // 更新了a 同样更新了arguments[0]
console.log(arguments[0]);
}
func(10); // 99
当非严格模式中的函数有包含剩余参数、默认参数和解构赋值,那么arguments
对象中的值不会跟踪参数的值
function func(a = 55) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
func(10); // 10
function func(a = 55) {
a = 99; // updating a does not also update arguments[0]
console.log(arguments[0]);
}
func(10); // 10
function func(a = 55) {
console.log(arguments[0]);
}
func(); // undefined
5、参考链接
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments