简体   繁体   中英

Why join() method returns different result than expected

As mentioned in w3schools join() method, joins all elements of an array into a string, and returns the string. So if you try the following:

console.log(new Array(6).join('a'));

I would expect to get: "aaaaaa" but instead I get: "aaaaa" , that means one less.

Can someone explain me why is that happening?

it puts the a between each element of your array, not after each one, so 6 elements has 5 joiners.

on this fiddle you can see a bit more exactly what the join is doing: http://jsfiddle.net/YKhmp/

Your array will start with six elements. Since you are joining with "a", the letter "a" will get added to the string between all of the elements.

If you had the two elements "Hello" and "World" in your array and joined with a hyphen, it would be joined "Hello-World". So, if you have an array of n values, it only has to be joined n-1.

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