Javascript method to convert an array into a string: 1. Use the join() function to connect the array elements with delimiters to build a string, the syntax format is "arr.join("separator") "; 2. Use toString() function, syntax format "String(arr)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use the join() function
join() to join the array elements with delimiters to build a string, syntax format:
arr.join("分隔符")
When calling the join() method, you can pass a parameter as a separator to join each element. If the parameter is omitted, commas are used as delimiters by default
var a = [1,2,3,4,5]; //定义数组 var s = a.join("=="); //指定分隔符 console.log(s); //返回字符串“1==2==3==4==5”
Method 2: Use toString() function
The toString() method in the array can convert each element into string and then concatenate the output with commas for display. Grammar format:
String(arr)
Example:
var a = [1,2,3,4,5,6,7,8,9,0]; //定义数组 var s = a.toString(); //把数组转换为字符串 console.log(s); //返回字符串“1,2,3,4,5,6,7,8,9,0” console.log(typeof s); //返回字符串string,说明是字符串类型
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of javascript how to convert array to string. For more information, please follow other related articles on the PHP Chinese website!