[英]Remove comma from string literal
I want to concatenate string with array Item.我想将字符串与数组项连接起来。
I tried following.我试着跟随。
const str = "I have following things:" const arr = ["chair", "table", "bed"]; const tootlTipText = `${str} ${arr.map(item => `- ${item} \n`)}`; console.log(tootlTipText);
It display, in between.它显示,介于两者之间。 I tried to find and can't find what is the issue.
我试图找到并找不到问题所在。
The problem is that by default, when you convert an array to a string, it's done as though you called .join(",")
.问题是,默认情况下,当您将数组转换为字符串时,就像您调用了
.join(",")
一样。 To avoid that, call join
yourself with whatever separator you want, perhaps ""
:为避免这种情况,请使用您想要的任何分隔符调用
join
自己,也许是""
:
const str = "I have following things:" const arr = ["chair", "table", "bed"]; const tootlTipText = `${str} ${arr.map(item => `- ${item} \n`).join("")}`; console.log(tootlTipText);
Alternatively, you could use a simple loop with string concatenation:或者,您可以使用带有字符串连接的简单循环:
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);
Some folks would also use reduce
for this;有些人也会为此使用
reduce
; personally I don't like reduce
except in functional programming with predefined, tested reducers, but:我个人不喜欢
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()
returns an array. Array.prototype.map()
返回一个数组。 It should be converted to string.它应该转换为字符串。
const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`).join('')}`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.