(六)js的arguments

  • arguments保存传入函数的所有参数
  • arguments是类数组对象,除length和索引(索引从0开始)之外无其他Array属性
  • arguments对象是所有(非箭头)函数中都可用的局部变量
  • 可以转化成一个真正的Array
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);
const args = [...arguments];
  • arguments.callee指向当前执行的函数
  • 严格模式下,剩余参数、默认参数和解构赋值参数的存在不会改变 arguments对象的行为
  • 非严格模式中的函数没有剩余参数、默认参数和解构赋值,那么arguments对象中的值会跟踪参数的值(反之亦然)
//ex1
function func(a) { 
  arguments[0] = 99;   // 更新了arguments[0] 同样更新了a
  console.log(a);
}
func(10); // 99

//ex2
function func(a) { 
  a = 99;              // 更新了a 同样更新了arguments[0] 
  console.log(arguments[0]);
}
func(10); // 99

  • 非严格模式中;函数包含剩余参数、默认参数和解构赋值,那么arguments对象中的值不会跟踪参数的值(反之亦然)
//ex1:包含解构赋值的默认值覆盖
function func(a = 55) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

//ex2:
function func(a = 55) { 
  a = 99; // updating a does not also update arguments[0]
  console.log(arguments[0]);
}
func(10); // 10

//ex3:
function func(a = 55) { 
  console.log(arguments[0]);
}
func(); // undefined
原文地址:https://www.cnblogs.com/smileyqp/p/12675337.html