Home > Web Front-end > JS Tutorial > body text

How to convert array to string in javascript

青灯夜游
Release: 2023-01-06 11:17:43
Original
4924 people have browsed it

Javascript method to convert array to string: 1. Use toString() method, syntax "arrayObject.toString()"; 2. Use join() method, syntax format "arrayObject.join(separator) )".

How to convert array to string in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Method 1. Use toString()

toString() method can convert the array into a string and return the result.

Syntax

arrayObject.toString()
Copy after login

Return value

String representation of arrayObject. The return value is the same as the string returned by the join() method without parameters.

Example

<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr.toString())
</script>
Copy after login

Output:

George,John,Thomas
Copy after login
Copy after login

Method 2, use join()

The join() method is used to put all elements in the array into a string.

Elements are separated by the specified delimiter.

Syntax

arrayObject.join(separator)
Copy after login
ParametersDescription
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.

Example

Example 1

In this example, we will create an array and put all its elements into a string:

<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr.join())
</script>
Copy after login

Output:

George,John,Thomas
Copy after login
Copy after login

Example 2

In this example, we will use delimiter to separate the elements in the array:

<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr.join("."))
</script>
Copy after login

Output:

George.John.Thomas
Copy after login

【Related recommendations: javascript learning tutorial

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!