简体   繁体   English

为什么 join() 方法返回的结果与预期不同

[英]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.

相关问题 toString() 返回与预期不同的值(但是 toFixed 返回正确的值)。 为什么? - toString() returns different value than expected (however toFixed returns the right one). Why? javascript function 返回的结果与预期不同 - javascript function return different result than expected AJAX返回的结果与浏览器不同 - AJAX returns a different result than the browser 为什么将 blob 转换为数据 URI 会导致与直接数据 URI 方法不同的 URI? - Why does converting a blob to a data URI result in a different URI than the direct data URI method? toDataURL返回与预期不同的base64值 - toDataURL returns different base64 value than expected Javascript window.atob - > HEX - 结果与预期不同 - Javascript window.atob -> HEX - different result than expected Dart compareTo() 有时返回与 javascript localeCompare() 不同的结果 - Dart compareTo() sometimes returns different result than javascript localeCompare() JavaScript localeCompare() 返回的结果与 Java compareTo() 不同 - JavaScript localeCompare() returns different result than Java compareTo() 为什么typeof的结果与传入的表达式的求值结果不同? - Why is typeof's result different than the evaluated result of the expression passed in? Javascript构造函数方法返回与预期不同的东西 - Javascript constructor method returning something different than expected
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM