在JavaScript中将数组转换为字符串

x33g5p2x  于2022-10-16 转载在 Java  
字(0.7k)|赞(0)|评价(0)|浏览(433)

在本教程中,我们向您展示了三种在JavaScript中将数组转换为字符串的方法。

1.使用join()方法
1.使用toString()方法
1.使用空字符串

1.使用join()方法

join()方法将元素数组转换为逗号分隔的字符串。
示例1:

const strArry = ['r','a','m', 'e', 's', 'h'];
console.log(strArry.join());

输出:

r,a,m,e,s,h

示例2:

const arr = ['r','a','m', 'e', 's', 'h', 1,2,3];
console.log(arr.join());

输出:

r,a,m,e,s,h,1,2,3

我们还可以将自己的分隔符作为参数传递给join()方法。
在下面的示例中,我们传递了-作为分隔符参数,以便字符串由减号运算符-分隔。
例子:

const arr = ['r','a','m', 'e', 's', 'h', 1,2,3];
console.log(arr.join('-'));

输出:

r-a-m-e-s-h-1-2-3

2.使用toString()方法

toString()方法还连接数组并返回字符串,其中元素数组由逗号分隔。
例子:

const strArry = ['r','a','m', 'e', 's', 'h'];
console.log(strArry.toString());

输出:

r,a,m,e,s,h

3.使用空字符串

如果添加一个带有空字符串“”的数组,它会将该数组转换为字符串。
例子:

const strArry = ['r','a','m', 'e', 's', 'h'];

console.log(strArry + '');

输出:

r,a,m,e,s,h

相关文章

微信公众号

最新文章

更多