参数 vs Array.prototype.slice.call(arguments,0)

arguments vs Array.prototype.slice.call(arguments,0)

在函数中使用参数和 Array.prototype.slice.call(arguments,0) 有什么区别? 我看不出两者之间有什么区别,所以我怎么知道什么时候应该使用哪一个?

function arr(){
  return arguments; // or return Array.prototype.slice.call(arguments,0);
}
arr([1,2,3],[4,5,6]);

区别在于arguments是一个"array-like"对象,不是数组。

您可以通过切片将 arguments 对象转换为真正的数组,就像这样

Array.prototype.slice.call(arguments, 0);

这为您提供了一个数组,具有 forEachpop 等数组属性,arguments 等对象没有(长度除外,arguments确实有)。

切片 arguments 对象通常(几乎)不是一个好主意,MDN 给出警告

You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example). Instead, try constructing a new array by iterating through the arguments object.

此外,应该没有真正需要将参数传递给函数,只需要传递给 return 它们。

参数对象不是真正的数组。它是一种特殊类型的对象,除了 "length" 之外没有任何 Array 属性。

要从参数对象创建数组,请使用 Array.prototype.slice.call(arguments, 0);

arguments 变量是 Object 的特殊类型,而不是 Array。所以,你不能用它来使用 .forEach.map、'.push' 和其他数组函数。

您必须将 arguments 转换为 Array 然后您可以将值用作数组

function test(){
  console.log(arguments.forEach); // undefined
  var argsArray = Array.prototype.slice.call(arguments,0);
  console.log(argsArray.forEach); // function
}
test();