Home >Web Front-end >JS Tutorial >How to convert array to string in javascript
Methods to convert arrays to strings in JavaScript: 1. Use the toString() function, which can convert each element in the array into a string, and then connect the output with commas. 2. Use the join() function, which converts all elements in the array into a string, and the elements are separated by the specified delimiter.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
Convert javascript array to string
Method 1: Use toString() function
The toString() method converts a Number object into a string and returns the result. The syntax is as follows:
number.toString(radix)
The toString() method in the array can convert each element into a string, and then connect the output with commas for display
Example:
var arr = [1,2,3,4,5]; //定义数组 var str = arr.toString();; console.log(str); console.log("str的数据类型:"+typeof(str));
Output:
#toString() When converting an array into a string, first convert each element of the array into a character string. When each element is converted to a string, it is separated by commas and output as a list.
var a = [1,[2,3],[4,5],[6,[7,[8,9],0]]]; //定义多维数组 var s = a.toString(); //把数组转换为字符串 console.log(s);
Output:
[Recommended learning: js basic tutorial]
Method 2: Use the join() function
The join() method is used to convert all elements in the array into a string. Elements are separated by the specified delimiter. The syntax is as follows:
array.join(separator)
separator: Optional. Specify the delimiter to use. If this parameter is omitted, a comma is used as the delimiter.
Return value:
Returns a string. The string is generated by converting each element of the arrayObject to a string and then concatenating the strings, inserting the separator string between the two elements.
Note: The
join() method can convert an array into a string, but it can specify the delimiter. When calling the join() method, you can pass a parameter as a separator to join each element. If the parameter is omitted, comma is used as the delimiter by default, which has the same conversion effect as the toString() method.
Example:
var arr = [1,2,3,4,5]; //定义数组 var str = arr.join(""); //指定分隔符 console.log(str); //返回字符串“12345” console.log("str的数据类型:"+typeof(str));
Output:
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of How to convert array to string in javascript. For more information, please follow other related articles on the PHP Chinese website!