"Array(n)"和"Array(n)"之间有什么区别?和"[... Array(n)]"? [英] What is the difference between "Array(n)" and "[...Array(n)]"?

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

问题描述

两者之间有什么区别?

// Chrome console

Array(2);                   // [undefined × 2]
Array(2).map(() => 1);      // [undefined × 2]

[...Array(2)];              // [undefined, undefined]
[...Array(2)].map(() => 1); // [1, 1]

基于什么是阵列空插槽?,似乎是与内存分配有关,但是为什么后一种情况下散布运算符突然导致要分配内存?

Based on What are Array empty slots?, it seems to be related to memory allocation, but why does the spread operator suddenly cause memory to be allocated in the latter case?

推荐答案

关于数组构造函数

所有这些调用都是等效的:

Regarding Array constructor

All these calls are equivalent:

  • Array(2)
  • 新数组(2)
  • var a = [];a.length = 2

从某种意义上说,它们是相等的,它们分配内存用于分配,但不创建索引.

They are equal in a sense that they allocate memory for assignment, but don't create the indexes.

Object.keys(Array(2))//[] .

这就是为什么当你这样做

That's why when you do

Array(2).map(()=> 1);//[undefined×2]

您基本上不需要进行任何更改,因为在数组上没有迭代发生,这是因为缺少 map 在数组上进行迭代时使用的迭代索引键.

you essentially change nothing, because no iteration happens over the array, because of lack of iteration index keys that map uses while iterating over the array.

... 运算符调用数组的 [Symbol.iterator] ,该数组是内置的 values()迭代器,并在甚至没有关键索引的情况下也可以得到相同的值.

... operator calls the [Symbol.iterator] of an array which is the built in values() iterator and iterates over values even with absent key indexes.

这就是为什么在结果中我们有了一个新数组,该数组具有明确的未定义值和适当的键索引.

That is why in the outcome we have a new array with distinct undefined values with key indexes in place.

Object.keys([... Array(2)])//["0","1"] .

此后, map 可以按预期的方式遍历键和相应的值.

After which map works as expected iterating over the keys and corresponding values.

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

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