为什么我需要复制一个数组才能使用它的方法? [英] Why do I need to copy an array to use a method on it?

查看:98
本文介绍了为什么我需要复制一个数组才能使用它的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 Array()来获得具有固定数量的未定义条目的数组。例如

I can use Array() to have an array with a fixed number of undefined entries. For example

Array(2); // [empty × 2] 

但是如果我去使用地图方法,比如说,我的新数组,条目仍未定义:

But if I go and use the map method, say, on my new array, the entries are still undefined:

Array(2).map( () => "foo");  // [empty × 2] 

如果我复制数组,那么地图确实有效:

If I copy the array then map does work:

[...Array(2)].map( () => "foo");  // ["foo", "foo"]

为什么我需要副本才能使用数组?

Why do I need a copy to use the array?

推荐答案

使用 Array(arrayLength)创建数组时,您将拥有

When you use Array(arrayLength) to create an array, you will have:


一个新的JavaScript数组,其length属性设置为该数字(注意:这意味着一个arrayLength空插槽数组,而不是实际未定义的插槽价值)。

a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).

数组实际上不包含任何值,甚至不包含 undefined 值 - 它只有一个长度属性。

The array does not actually contain any values, not even undefined values - it simply has a length property.

当你传播一个可迭代的对象具有 length 属性到数组中,spread语法访问每个索引并在新数组中设置该索引处的值。例如:

When you spread an iterable object with a length property into an array, spread syntax accesses each index and sets the value at that index in the new array. For example:

const arr1 = [];
arr1.length = 4;
// arr1 does not actually have any index properties:
console.log('1' in arr1);

const arr2 = [...arr1];
console.log(arr2);
console.log('2' in arr2);

.map 仅映射属性实际存在于要映射的数组中的属性/值。

And .map only maps properties/values for which the property actually exists in the array you're mapping over.

使用数组构造函数会让人感到困惑。我建议使用 Array.from 代替,从头开始创建数组时 - 你可以传递一个长度的对象属性,以及映射函数:

Using the array constructor is confusing. I would suggest using Array.from instead, when creating arrays from scratch - you can pass it an object with a length property, as well as a mapping function:

const arr = Array.from(
  { length: 2 },
  () => 'foo'
);
console.log(arr);

这篇关于为什么我需要复制一个数组才能使用它的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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