join()
方法通过连接数组中的所有元素,并由指定的字符串分隔,返回一个新的字符串。
示例
let message = ["JavaScript", "is", "fun."];
// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);
// Output: JavaScript is fun.
join() 语法
join()
方法的语法是:
arr.join(separator)
这里,arr 是一个数组。
join() 参数
join()
方法接受:
- separator (可选) - 用于分隔数组中每对相邻元素的字符串。默认值为逗号
,
。
join() 返回值
- 返回一个由 separator 分隔的、所有数组元素连接而成的 字符串。
注意事项:
join()
方法不会改变原始数组。- 像
undefined
、null
或空数组这样的元素,它们的字符串表示为空字符串。
示例:使用 join() 方法
var info = ["Terence", 28, "Kathmandu"];
var info_str = info.join(" | ");
// join() does not change the original array
console.log(info); // [ 'Terence', 28, 'Kathmandu' ]
// join() returns the string by joining with separator
console.log(info_str); // Terence | 28 | Kathmandu
// empty argument = no separator
var collection = [3, ".", 1, 4, 1, 5, 9, 2];
console.log(collection.join("")); // 3.141592
var random = [44, "abc", undefined];
console.log(random.join(" and ")); // 44 and abc and
输出
[ 'Terence', 28, 'Kathmandu' ] Terence | 28 | Kathmandu 3.141592 44 and abc and
在这里,我们可以看到 join()
方法将所有数组元素转换为字符串,并用指定的字符串分隔每个元素。
另请阅读