我想用数组Item连接字符串。
我尝试关注。
const str = "I have following things:"
const arr = ["chair", "table", "bed"];
const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`)}`;
console.log(tootlTipText);
它之间显示。我试图找到但找不到问题所在。
答案 0 :(得分:6)
问题在于,默认情况下,当您将数组转换为字符串时,就好像调用了.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
,除了在带有预定义的,经过测试的减速器的函数式编程中,但是:
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);
答案 1 :(得分:2)
Array.prototype.map()
返回一个数组。应该将其转换为字符串。
const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`).join('')}`;