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

javascript how to convert array to string

青灯夜游
Release: 2023-01-06 11:13:56
Original
55327 people have browsed it

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("分隔符")
Copy after login

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”
Copy after login

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)
Copy after login

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,说明是字符串类型
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template