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/