javascript - 从字符串文字中删除逗号
问题描述
我想将字符串与数组项连接起来。
我试着跟随。
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);
推荐阅读
- javascript - 如何在 Google Chrome 中使用 iframe 查看包含 JQuery 的网页
- r - 使用 R 中的 Leaflet 从 shapefile 获取经度和纬度
- javascript - React 路由器在每次更新时卸载和重新安装子组件
- php - 从codeigniter php编译.docx文件时出现问题
- sql-server - SQL Server:通过设置参数或配置服务器检索值时,从 CHAR 列中删除尾随空格
- java - lombok builder和lombok no//allargsconstructor annotation之间的性能哪个更好
- reactjs - 使用 React HOC 模式,为什么返回一个组件与返回一个函数返回一个 JSX 组件一样?
- android - Android Studio 布局问题
- c++ - 在共享库中使用重载的 new/delete 和 STL
- javascript - 内容超过标题