Array.apply(null,Array(x))和Array(x)之间的区别 [英] Difference between Array.apply(null, Array(x) ) and Array(x)

查看:248
本文介绍了Array.apply(null,Array(x))和Array(x)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间究竟有什么区别:

Array(3)
// and
Array.apply(null, Array(3) )

第一个返回 [undefined x 3] 而第二个返回 [undefined,undefined,undefined] 。第二个可以通过 Array.prototype.functions 链接,例如 .map ,但第一个不是。为什么?

The first returns [undefined x 3] while the second returns [undefined, undefined, undefined]. The second is chainable through Array.prototype.functions such as .map, but the first isn't. Why?

推荐答案

存在差异,非常重要。

数组构造函数 接受一个数字,给出数组的长度,以及一个数组空索引已创建,或更正确地设置长度但数组实际上不包含任何内容

The Array constructor either accepts one single number, giving the lenght of the array, and an array with "empty" indices is created, or more correctly the length is set but the array doesn't really contain anything

Array(3); // creates [], with a length of 3

当使用数字作为数组调用数组构造函数时只有参数,你创建一个空的数组,并且不能使用通常的Array方法迭代。

When calling the array constructor with a number as the only argument, you create an array that is empty, and that can't be iterated with the usual Array methods.

... Array构造函数接受多个参数,而创建一个数组,其中每个参数都是数组中的值

Or... the Array constructor accepts several arguments, whereas an array is created where each argument is a value in the array

Array(1,2,3); // creates an array [1,2,3] etc.

当你调用这个

Array.apply(null, Array(3) )

它变得更有趣了。

apply 接受值作为第一个参数,因为它在这里没用,它被设置为 null

apply accepts the this value as the first argument, and as it's not useful here, it's set to null

有趣的部分是第二个参数,其中一个正在传入空数组。

apply 接受一个数组就像调用

The interesting part is the second argument, where an empty array is being passed in.
As apply accepts an array it would be like calling

Array(undefined, undefined, undefined);

并创建一个包含三个不为空的索引但实际设置为<$的值的数组c $ c> undefined ,这就是它可以迭代的原因。

and that creates an array with three indices that's not empty, but have the value actually set to undefined, which is why it can be iterated over.

TL; DR

主要区别在于 Array(3)创建一个三个索引为空的数组。实际上,它们并不存在,数组的长度只有 3

TL;DR
The main difference is that Array(3) creates an array with three indices that are empty. In fact, they don't really exist, the array just have a length of 3.

使用 apply 将具有空索引的数组传递给Array构造函数与执行<$ c相同$ c> Array(undefined,undefined,undefined); ,它创建一个包含三个 undefined 索引的数组,以及 undefined 实际上是一个值,所以它不像第一个例子那样是空的。

Passing in such an array with empty indices to the Array constructor using apply is the same as doing Array(undefined, undefined, undefined);, which creates an array with three undefined indices, and undefined is in fact a value, so it's not empty like in the first example.

map()这样的数组方法只能迭代实际值,而不是空索引。

Array methods like map() can only iterate over actual values, not empty indices.

这篇关于Array.apply(null,Array(x))和Array(x)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆