JavaScript - 数组 join() 方法
JavaScript Array join() 方法用于使用指定的分隔符连接数组元素,并以字符串形式返回结果。
- 如果未指定分隔符,则数组元素默认以逗号 (,) 分隔。
- 此方法不会更改原始数组,而是返回一个新的字符串作为结果。
- 如果数组只有一个元素,则返回值不带分隔符。
语法
以下是 JavaScript Array join() 方法的语法 -
array.join(separator);
参数
此方法仅接受一个参数。如下所示:
- "separator" 是一个字符串,用于分隔结果字符串中的元素。默认情况下,它使用逗号 (,) 分隔。
返回值
一个字符串,表示由指定分隔符连接的数组元素。
示例
示例 1
如果我们没有向 JavaScript 数组 copyWithin() 方法传递任何分隔符,它将默认使用逗号 (,) 分隔元素。
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
let result = animals.join();
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
正如我们在输出中看到的,数组中的所有元素都用逗号 (,) 分隔。
Lion,Chetaah,Tiger,Elephant,Dinosaur
示例 2
在这里,我们将一个空字符串作为参数传递给此函数。这样,它将返回不带逗号 (,) 且元素之间没有空格的元素 -
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
let result = animals.join("");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
执行上述程序后,数组元素之间将无空格分隔。
LionChetaahTigerElephantDinosaur
示例 3
这里,我们将"and"作为分隔符传递给此函数。这样,数组元素将由"and"分隔 -
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
let result = animals.join(" and ");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
执行上述程序后,数组元素将以"and"分隔。
Lion and Chetaah and Tiger and Elephant and Dinosaur

