在分配新的JavaScript数组 [英] Allocate new array in javascript

查看:101
本文介绍了在分配新的JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图与价值分配新的数组。

案例1:

 变种x =新的Array(3).MAP(()=> 1);

现在 X [不确定* 3]

2种情况:

  VAR X = [...新的Array(3)图(()=> 1)。

现在 X [1,1,1]

有人能帮助吗?

为什么用这个的取值$ P $垫运营商让这样的区别?

为什么案例1 不起作用


解决方案

TL;博士:第一个数组有洞,第二个没有。 .MAP 跳过孔。


通过使用A S $ P $垫件,数组被视为的迭代的,即你得到一个迭代器遍历数组。迭代器基本上就像一个循环,它将从指数 0 数组迭代指数 array.length - 1 (见规范获取详细信息),并且每个索引到新的数组中添加值。由于您的阵列不包含任何值,数组[我] 将返回未定义为每个索引。

这意味着, [...新的Array(3)] 的结果,从字面上包含三个未定义的数组值,而不是长度的只是一个备用数组 3

在Chrome中看到的区别:

我们称之为稀疏矩阵也阵列,

这是症结所在:许多阵列的方法,包括 .MAP 跳过洞!他们不把孔为值未定义,完全忽略它。

您可以轻松验证通过把一个的console.log .MAP 回调:

\r
\r

阵列(3).MAP(()=>的console.log('打给我'));\r
//没有输出

\r

\r
\r

这是你的第一个例子不工作的原因。你有一个稀疏数组,只有孔,其中 .MAP 忽略。创建有s $ P $垫元素的新Array创建无孔阵列,因此 .MAP

Trying to allocate new array with values.

Case 1 :

var x = new Array(3).map(()=>1);

Now x is [undefined * 3]

Case2 :

var x = [...new Array(3)].map(()=>1);

And now x is [1,1,1]

Can someone help here?

Why using this spread operator makes such a difference?

And why Case 1 doesn't work ?

解决方案

tl;dr: The first array has holes, the second one doesn't. .map skips holes.


By using a spread element, the array is treated as an iterable, i.e. you get an iterator to iterate over the array. The iterator basically works like a for loop, it will iterate the array from index 0 to index array.length - 1 (see the spec for details), and add the value at each index to the new array. Since your array doesn't contain any values, array[i] will return undefined for every index.

That means, [...new Array(3)] results in an array that literally contains three undefined values, as opposed to just a "spare" array of length 3.

See the difference in Chrome:

We call "sparse arrays" also "arrays with holes".

Here is the crux: Many array methods, including .map, skip holes! They are not treating the hole as the value undefined, the completely ignore it.

You can easily verify that by putting a console.log in the .map callback:

Array(3).map(() => console.log('call me'));
// no output

And that's the reason your first example doesn't work. You have a sparse array with only holes, which .map ignores. Creating a new array with the spread element creates an array without holes, hence .map works.

这篇关于在分配新的JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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