Skip to content

Arguments

在 JavaScript 中,arguments 是传递给函数的实际参数列表, 是一个类数组(like-array)对象, 这意味 arguments 有着 length 属性,而没有 Array 的相关方法。

注意:箭头函数没有 arguments 局部变量。

转换成 Array

我们可以先将 arguments 转换为数组,然后调用数组的方法。

javascript
function fn() {
  const args = Array.prototype.slice.call(arguments);
  // ES 2015
  const args2 = Array.from(arguments);
  // 想获得更好的性能可以使用 Array 构造函数+
  const args3 = Array.call(null, arguments);
}

获得函数签名中参数的个数

javascript
function add(a, b) {
  // 始终输出 2,length 只与函数签名中的参数个数有关。
  console.log(add.length);
}

严格模式

严格模式下,无法通过 函数名.arguments 访问 arguments 属性,但是可以直接访问 arguments 局部变量。

javascript
function tester() {
  'use strict';
  console.log(Array.from(arguments)); // No error
  console.log(tester.arguments); // -> Referencing 'arguments' function property is not allowed
}