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(",")
. To avoid that, call join
yourself with whatever separator you want, perhaps ""
:
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; personally I don't like reduce
except in functional programming with predefined, tested reducers, but:
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. It should be converted to string.
const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`).join('')}`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.