CV工程师
2022-06-06 01:12:28 阅读:750
要将数组转换为JavaScript中不带逗号的字符串,请对数组调用join()方法,并将空字符串('')作为参数传递:
const arr = ['coffee', 'milk', 'tea'];
const withoutCommas = arr.join('');
console.log(withoutCommas); // coffeemilktea
Array.join()方法返回一个字符串,其中包含与指定分隔符连接的每个数组元素。如果没有分隔符作为参数传递,它将使用逗号连接数组元素:
const arr = ['coffee', 'milk', 'tea'];
const str = arr.join();
console.log(str); // coffee,milk,tea
除了空字符串之外,我们还可以指定其他分隔符,如连字符和斜杠:
const arr = ['coffee', 'milk', 'tea'];
const withHypens = arr.join('-');
console.log(withHypens); // coffee-milk-tea
const withSlashes = arr.join('/');
console.log(withSlashes); // coffee/milk/tea
const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee milk tea
分隔符还可以包含多个字符:
const arr = ['coffee', 'milk', 'tea'];
const withAnd = arr.join(' and ');
console.log(withAnd); // coffee and milk and tea
const withOr = arr.join(' or ');
console.log(withOr); // coffee or milk or tea
如果数组中有undefined或者是null时,则在与分隔符串联之前,将其转换为空字符串('')。例如:
const arr = ['coffee', null, 'milk', []];
const withComma = arr.join(',');
console.log(withComma); // coffee,,milk,
const withHyphen = arr.join('-');
console.log(withHyphen); // coffee--milk-
评论
扫描二维码获取文章详情
更多精彩内容尽在:WWW.ZNGG.NET