Array.apply(null, obj)的原理是什么?

What's the principle of Array.apply(null, obj)?

let a = {0: 'a', 1: 'b', length: 2}
Array.apply(null, a) // ['a', 'b']

使用数组构造函数是将类数组对象转换为数组的最快方法,例如jsperf

我想弄清楚它是如何工作的,但我失败了。在ECMAScript-262中,我找不到相应的方法来解释该代码。

为什么 Array 构造函数接受类数组对象可以将其转换为 Array。

Why does Array.apply(null, [args]) act inconsistently when dealing with sparse arrays?

使用 apply() 您可以调用一个函数并传递应该用作类数组对象的参数。

所以Array.apply(null, {0: 'a', 1: 'b', length: 2})等同于Array('a','b')

并且可以使用 (MDN - Array):

构造数组
new Array(element0, element1[, ...[, elementN]])

并且由于数组属于那些可以在没有 new 的情况下构造的对象,给定的代码将构造具有这些元素的数组。

使用Function#apply(), the second parameter takes an . An array-like is basically an object that has numeric keys and a length property but isn't necessarily an array - for example the arguments object is an array-like时。

然后该参数将提供给您调用 apply 的函数,就好像它是该函数的所有参数一样:

function foo(one, two, three) {
  console.log("one:", one);
  console.log("two:", two);
  console.log("three:", three);
}
//normal invocation
foo("hello", "world", "!");

//.apply using an array-like
foo.apply(null, {0: "nice", 1: "meeting", 2: "you", length: 3});

//.apply using an array
foo.apply(null, ["see", "you", "later"]);

因此,当您调用 Array.apply(null, {0: 'a', 1: 'b', length: 2}) 时,它等效于调用 Array('a', 'b') - using the array constructor 具有多个参数,从这些参数生成一个数组:

console.log(Array("a", "b"));

因此,当您在构造函数上调用 apply 时,您会得到该行为。

在 ES6 中,将数组作为第二个参数传递给 .apply 几乎与使用扩展语法相同:

function foo(one, two, three) {
  console.log("one:", one);
  console.log("two:", two);
  console.log("three:", three);
}

const arrayArgs = ["hello", "world", "!"];
foo(...arrayArgs);

但是,这不适用于类数组:

function foo(one, two, three) {
  console.log("one:", one);
  console.log("two:", two);
  console.log("three:", three);
}

const arrayLikeArgs = {0: "hello", 1: "world", 2: "!", length: 3};
foo(...arrayLikeArgs);