繁体   English   中英

从字符串文字中删除逗号

[英]Remove comma from string literal

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

我试着跟随。

 const str = "I have following things:" const arr = ["chair", "table", "bed"]; const tootlTipText = `${str} ${arr.map(item => `- ${item} \n`)}`; console.log(tootlTipText);

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

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

Array.prototype.map()返回一个数组。 它应该转换为字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM