《现代JavaScript教程》Arguments

首先我们必须承认arguments 不是一个很好的设计,这是因为它是一个类数组对象,类数组意味着它有leng属性和从0开始索引的属性。但又不支持Array对象的像是forEach或者map方法。如果你在写ES6代码,那么更推荐使用剩余参数。所以我在这里不会详细展开介绍arguments 。

 

arguments 是一个对应于传递给函数的参数的类数组对象。所以你可以将它转换为真正的数组对象来使用。

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);
const args = [...arguments];

 

arguments对象可以与剩余参数、默认参数和解构赋值参数结合使用。

在严格模式下,剩余参数、默认参数和解构赋值参数的存在不会改变 arguments对象的行为。

当非严格模式中的函数没有包含剩余参数、默认参数和解构赋值,那么arguments对象中的值会跟踪参数的值(反之亦然)。

 

没有包含剩余参数、默认参数和解构赋值:

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


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

 

包含剩余参数、默认参数和解构赋值:

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

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

 

posted @ 2021-11-20 16:49  丸子球球  阅读(36)  评论(0编辑  收藏  举报