Home  >  Article  >  Web Front-end  >  JavaScript join() method to put all elements in an array into a string

JavaScript join() method to put all elements in an array into a string

黄舟
黄舟Original
2017-11-03 10:28:264619browse

Definition and usage

join() method is used to put all elements in 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, then concatenating the strings, and inserting a separator string between the two elements. Example

Example 1

In this example, we will create an array and then 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 the 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

The following are the details of the parameters:

    separator : 指定字符串分开数组的每个元素。如果省略,则数组元素用逗号分隔。

Return value:

Returns the string after joining all array elements.

Example:

<html>
<head>
<title>JavaScript Array join Method</title>
</head>
<body>
<script type="text/javascript">
 
var arr = new Array("First","Second","Third");
 
var str = arr.join();
document.write("str : " + str ); 
 
var str = arr.join(", ");
document.write("<br />str : " + str ); 
 
var str = arr.join(" + ");
document.write("<br />str : " + str ); 
</script>
</body>
</html>

This will produce the following results:

str : First,Second,Third
str : First, Second, Third
str : First + Second + Third

The above is the detailed content of JavaScript join() method to put all elements in an array into a 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