首页 > 解决方案 > 从字符串文字中删除逗号

问题描述

我想将字符串与数组项连接起来。

我试着跟随。

const str = "I have following things:"
const arr = ["chair", "table", "bed"];


const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`)}`;
                

console.log(tootlTipText);

它显示 , 介于两者之间。我试图找到并找不到问题所在。

标签: javascript

解决方案


问题是,默认情况下,当您将数组转换为字符串时,就像您调用.join(","). 为避免这种情况,请join使用您想要的任何分隔符来称呼自己,也许是""

const str = "I have following things:"
const arr = ["chair", "table", "bed"];


const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`).join("")}`;
                

console.log(tootlTipText);

或者,您可以使用带有字符串连接的简单循环:

const str = "I have following things:"
const arr = ["chair", "table", "bed"];

let tootlTipText = `${str}\n`;
for (const item of arr) {
    tootlTipText += `- ${item} \n`;
}

console.log(tootlTipText);

有些人也会reduce为此使用;我个人不喜欢reduce使用预定义的、经过测试的 reducer 进行函数式编程,但是:

const str = "I have following things:"
const arr = ["chair", "table", "bed"];

const tootlTipText = arr.reduce(
    (str, item) => str + `- ${item} \n`,
    `${str}\n`
);

console.log(tootlTipText);


推荐阅读