简体   繁体   中英

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 ? 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. So, the join method will first transform it to a string: '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 :

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. 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. In case you will pass it an array, JavaScript will convert this array into a string internally by calling .toString() method of Arrays. And this returned string ie d,e,f will be used as a separator to join elements in outer array.

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