Let’s start with a piece of code
const array = new Array(5).map((item) => {
return item = {
name: 'stone'}}); console.log(array);Copy the code
Thought of the result: [{name: “stone”}, {name: “stone”}, {name: “stone”}, {name: “stone”}, {name: ‘stone’}]
Actual result: [undefined × 5]
what the fuck??? Black mark
I think the reason is: since the value in our array is undefined, we can’t assign undefined. Okay, so let’s test my guess.
const array = [undefined, undefined, undefined, undefined, undefined];
const newArr = array.map((item) => {
return item = {
name: 'stone'}}); console.log(newArr);Copy the code
Output results:
what the fuck??? Black mark
What causes this
So it is: developer.mozilla.org/en-US/docs/…
The new Array(x) operation does not create an Array where all x items are undefined. Instead, it creates an Array of only length, each item of which has no assigned value. (Imagine that new Array(5) actually creates an Array of [,,,,,].
const array = [ , , , , , ];
const newArr = array.map((item) => {
return item = {
name: 'stone'}}); console.log(newArr);Copy the code
Output: [undefined * 5]
So to summarize: the map function’s callback is only called for assigned items. New Array(1) is different from [undefined]. New Array(1) does not assign a value to an item in the Array, whereas [undefined] assigns a value of undefined to an item in the Array.
The solution
const array = new Array(5).fill().map((item) => {
return item = {
name: 'stone'}}); console.log(array);Copy the code