[英]How Array.join works if separator is an array in Javascript?
i can't understand how Array.join works if separator is an array in Javascript ? 如果分隔符是Javascript中的数组,我无法理解Array.join如何工作? I find a detail explanation how it works.
我找到了详细的解释,它是如何工作的。 My example below
我下面的例子
arr1 = ['a','b','c'];
arr2 = ['d', 'e', 'f'];
arr1.join(arr2);
//Output
"ad,e,fbd,e,fc"
The join method accepts a separator and you're passing an array as separator. join方法接受一个分隔符,并且您要传递一个数组作为分隔符。 So, the join method will first transform it to a string: 'd,e,f'
因此,join方法将首先将其转换为字符串:'d,e,f'
Thus, 从而,
ad,e,f
bd,e,f
c // last remains same - no join
// as you may do like ['a','b','c'].join('-') results a-b-c
And final result: 最终结果:
ad,e,fbd,e,fc
You may read this note on docs : 您可以在docs上阅读此说明:
Separator 分隔器
Specifies a string to separate each pair of adjacent elements of the array.
指定一个字符串来分隔数组的每对相邻元素。 The separator is converted to a string if necessary.
如果需要,分隔符将转换为字符串。 If omitted, the array elements are separated with a comma (",").
如果省略,则数组元素用逗号(“,”)分隔。 If separator is an empty string, all elements are joined without any characters in between them.
如果分隔符为空字符串,则所有元素之间都将没有任何字符地连接在一起。
JavaScript is a flexible language. JavaScript是一种灵活的语言。 If it will receive something other than it is expecting, it will try to convert the passed value into a form / type that it is expecting.
如果它将收到预期以外的内容,它将尝试将传递的值转换为预期的格式/类型。
As from Docs , Array's .join()
method expects a string in argument to be used as a separator for joining array elements. 从Docs开始 ,Array的
.join()
方法期望参数中的字符串用作连接数组元素的分隔符。 In case you will pass it an array, JavaScript will convert this array into a string internally by calling .toString()
method of Arrays. 万一您将其传递给数组,JavaScript会通过调用Arrays的
.toString()
方法将该数组内部转换为字符串。 And this returned string ie d,e,f
will be used as a separator to join elements in outer array. 返回的字符串
d,e,f
将用作分隔符,以连接外部数组中的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.