Difference between Array.prototype.slice.call (arguments) and Array.apply (null, arguments)

As far as I can tell, these two functions behave the same:

function returnArgs() { return Array.prototype.slice.call(arguments) };

function returnArgs2() { return Array.apply(null, arguments) };

I see both approaches referenced by all of SO, but still don't understand why you are using one of them. Is this a preference, or is there more practical power in the game? Perhaps I am missing the obvious difference?

+4
source share
1 answer

The second is quite dangerous and will not always work. Try:

console.log(returnArgs2(3));

This will show an empty array of length 3. The Array constructor interprets one numeric argument as meaning that you need an array of this length.

edit — , , "" , "" arguments, , arguments , arguments . , :

function returnArgs() {
  var rv = [];
  for (var i = 0; i < arguments.length; ++i)
    rv.push(arguments[i]);
  return rv;
}

arguments.length , arguments, , . , " " , .

"" arguments , . :

function foo(a, b) {
  arguments[1] = a;
  return b;
}

alert(foo("hello", "world")); // "hello"

arguments[1] , b . , arguments "" , , ( ), .

, V8, . Nashorn, JDK 8, , , arguments .

+4

Source: https://habr.com/ru/post/1540573/


All Articles