javascript - when I create an array of empty items, I can't use map with it - Stack Overflow

I tried this> Array(3)[ <3 empty items> ]>and this joins up all the nothings> Arr

I tried this


> Array(3)
[ <3 empty items> ]
> // and this joins up all the nothings
> Array(3).join('-')
'--'
> // but...
> Array(3).map((x) => 'a')
[ <3 empty items> ]
> // map doesn't work with the array of empty items!

and I thought I would get the same result as this

> [undefined, undefined, undefined].map((x) => 'a')
[ 'a', 'a', 'a' ]

What's up with that?

I tried this


> Array(3)
[ <3 empty items> ]
> // and this joins up all the nothings
> Array(3).join('-')
'--'
> // but...
> Array(3).map((x) => 'a')
[ <3 empty items> ]
> // map doesn't work with the array of empty items!

and I thought I would get the same result as this

> [undefined, undefined, undefined].map((x) => 'a')
[ 'a', 'a', 'a' ]

What's up with that?

Share Improve this question asked Jan 29, 2021 at 13:53 Alex028502Alex028502 3,8442 gold badges29 silver badges58 bronze badges 7
  • 4 The .map() method (and others like it) skip uninitialized array positions. – Pointy Commented Jan 29, 2021 at 13:55
  • 1 Try Array(3).fill(null).map(x => 'a') – Pointy Commented Jan 29, 2021 at 13:56
  • thanks! that's funny how join is cool with it – Alex028502 Commented Jan 29, 2021 at 13:56
  • 1 See: Why do I need to copy an array to use a method on it? – Nick Parsons Commented Jan 29, 2021 at 13:58
  • 1 Thanks - I couldn't even think how to search for this! – Alex028502 Commented Jan 29, 2021 at 14:00
 |  Show 2 more ments

2 Answers 2

Reset to default 5

you can use :

Array(3).fill(null).map(x => 'a')

in the first case you creates an array with undefined pointers.

Array(3)

And the second creates an array with pointers to 3 undefined objects, in this case the pointers them self are NOT undefined, only the objects they point to.

[undefined, undefined, undefined]

when we pare the two case it's look like this

//first case look like this 
[undefined, undefined, undefined]
//the second look like this 
 Array(3) [,,,];

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. In the first case array values have not explicitly assigned values, whereas in the seconds example were assigned, even if it was the value undefined link

for you example you have to do this

Array(3).fill(undefined).map(x => 'a')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745418075a4626841.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信