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

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

问题描述

我可以使用 Array() 来获得一个包含固定数量未定义条目的数组.例如

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

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

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

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] 

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

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 值 - 它只有一个 length 属性.

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

当您将具有 length 属性的可迭代对象展开到数组中时,展开语法会访问每个索引并在新数组中设置该索引处的值.例如:

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 代替,当从头开始创建数组时 - 您可以将具有 length 属性的对象以及映射函数传递给它:

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天全站免登陆