Home > Web Front-end > JS Tutorial > 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

黄舟
Release: 2017-11-03 10:28:26
Original
4675 people have browsed it

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

Output:

George,John,Thomas
Copy after login

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

Output:

George.John.Thomas
Copy after login

The following are the details of the parameters:

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

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

This will produce the following results:

str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
Copy after login

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!

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