Home  >  Article  >  Web Front-end  >  javascript how to convert array to string

javascript how to convert array to string

青灯夜游
青灯夜游Original
2021-05-18 16:09:2055313browse

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)".

javascript how to convert array to string

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn