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

How to convert array to string in javascript

青灯夜游
青灯夜游Original
2021-06-17 16:34:394962browse

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()

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>

Output:

George,John,Thomas

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)
Parameters Description
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>

Output:

George,John,Thomas

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>

Output:

George.John.Thomas

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

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