Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - Why do I need to copy an array to use a method on it?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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).

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

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...