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

标签 javascript arrays ecmascript-6 ecma262

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

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

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

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

Difference between Array.apply(null, Array(x) ) and Array(x)

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

最佳答案

当使用Function#apply()时,第二参数采用 array-like 。类数组基本上是一个具有数字键和 length 属性的对象,但不一定是数组 - 例如 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);

关于javascript - Array.apply(null, obj) 的原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497044/

相关文章:

arrays - Matlab all() 函数行号

Angular 9 警告 typescript.js

javascript - 我可以将完整的商店对象从容器发送到操作创建者(React/Redux)吗

javascript - Ember.TEMPLATES 为空 (ember-cli-htmlbars)

javascript - 当鼠标悬停在单词上时获取单词

javascript - 从数组中选择所有键为 : name is equal something 的内容

javascript - 获取两个对象数组之间差异的有效方法?

javascript - 通过的 react 组件在表单标签的可访问性单元测试中失败了吗?

javascript - Chart.js + Angular 5 - Destroy() 通过 *ngFor 循环创建的多个动态图表

javascript - AJAX 聊天的正确刷新率是多少?