arguments 与 剩余参数(...args) 的区别

本文主要介绍 arguments 与 剩余参数(…args) 的区别。

区别

  • arguments 为类数组, 只有 length 属性; 剩余参数为数组, 可使用全部数组的方法
  • arguments 包含所有函数实参, 剩余参数只包含没有对应形参的实参
  • arguments 具有一些特别的属性(callee)

examples

1
2
3
4
5
6
7
8
9
10
function test(a, ...args) {
console.log(a) // 1
console.log(arguments) // [1, 2, 3]
console.log(Array.isArray(arguments)) // false
console.log(Array.prototype.slice.call(arguments)) // [1, 2, 3]
console.log(Array.isArray(Array.prototype.slice.call(arguments))) //true
console.log(args) // [2, 3]
}

test(1, 2, 3)

arguments转数组

1
2
var args = Array.from(arguments);
var args = [...arguments];