开发者

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 expl开发者_Go百科ain 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜