简体   繁体   中英

Array method and join function combined output in javascript unable to understand

I defined myArr variable in javascript as follows:

var myArr= Array(3);

When I consoled the value of myArr it gave the following output:

[undefined × 3]

When I used the javascript join function which is as follows:

myArr.join('X');

And consoled the output I got the following:

"XX"

Can somebody explain me why I got this output? I was expecting the output to be

"undefinedXundefinedX"

Array(3) creates an array of three empty holes .

To achieve your desired result, you need to fill the holes: Array(3).fill()

Array.prototype.join will perform the string conversions of all array elements and joined into one string. If an element is undefined or null, it is converted to the empty string. join

All the undefined elements are equal to ["", "", ""].join('X')

Array(3) will create an array of length 3.

On consoling myArr it will log empty array

join will join all elements of the array into a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM