从字符串文字中删除逗号

ket*_*tan 2 javascript

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

我试着跟随。

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


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

console.log(tootlTipText);
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 5

问题是,默认情况下,当您将数组转换为字符串时,就像调用.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);
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

有些人也会用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);
Run Code Online (Sandbox Code Playgroud)