[英]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.如w3schools join() 方法中所述,将数组的所有元素连接成一个字符串,并返回该字符串。 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.我希望得到:
"aaaaaa"
,但我得到: "aaaaa"
,这意味着少了一个。
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.它将 a 放在数组的每个元素之间,而不是在每个元素之后,因此 6 个元素有 5 个连接器。
on this fiddle you can see a bit more exactly what the join is doing: http://jsfiddle.net/YKhmp/在这个小提琴上,你可以更准确地看到连接在做什么: 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.
由于您使用“a”连接,因此字母“a”将添加到所有元素之间的字符串中。
If you had the two elements "Hello" and "World" in your array and joined with a hyphen, it would be joined "Hello-World".如果您的数组中有两个元素“Hello”和“World”并用连字符连接,它将被连接到“Hello-World”。 So, if you have an array of n values, it only has to be joined n-1.
因此,如果您有一个包含 n 个值的数组,则只需将其连接为 n-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.