簡體   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