JS基础篇:11、简单易懂arguments

208 阅读1分钟

定义

arguments 是一个对应于传递给函数的参数的类数组对象。

特性

  • arguments是所有(非箭头)函数中都可用的局部变量。
  • arguments对象不是一个 Array。它类似于Array,但除了length属性和索引之外没有任何Array属性
function fn(a, b, c) {
  console.log(arguments[0]); // 1

  console.log(arguments[1]); // 2

  console.log(arguments[2]); // 3
  
  console.log(arguments); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
  
  console.log(arguments.callee); // 指向调用当前方法的函数
  
  console.log(typeof(arguments)); // object
}

fn(1, 2, 3);

转真实数组

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

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