gpt4 book ai didi

javascript - 映射到 json 并使用 javascript 转换为 html 时得到额外的逗号

转载 作者:行者123 更新时间:2023-11-30 20:14:55 25 4
gpt4 key购买 nike

我正在做一个爱好项目来制作一个站点生成器,该站点生成器使用 node fs-extra 模块读取 json 文件,然后将该数据传递给一个函数,该函数使用模板文字构建一个 html 文件,但我一直在得到一堆逗号我的HTML。有谁知道为什么会发生这种情况,或者可以帮助我找到解决方案来解决这个问题?

使用fs包写入文件

              <nav>
${
`<ul class='nav-list'>
${navList.map(navItem =>{
return (`<li>
<a href="${
navItem.folder+"/" + navItem.title +".html"
}">
${navItem.navTitle}
</a>
<li>`)
})}
</ul>
`
}
</nav>

这是它输出的带有额外逗号的 HTML - 我有另一种情况,其中有更多标签具有相同的逗号问题(为简单起见添加了这个)输出:

<nav>
<ul class='nav-list'>
<li>
<a href="./root/Index.html">
Home
</a>
<li>,<li>
<a href="./section1/Index2.html">
Section1
</a>
<li>
</ul>

</nav>

这是我在映射上面记录 navList 时我的终端输出的内容(在 JSON.parse() 之后)

[ { title: 'Index', folder: 'root', navTitle: 'Home' },

{ title: 'Index2', folder: 'section1', navTitle: 'Section1' } ]

提前致谢(上面一行不在代码块中的是代码块的一部分)

最佳答案

这些逗号来自数组到字符串的隐式转换。如果你不想要这些逗号,你应该明确地将数组转换为你想要的字符串 (join(""))

Would you do this before passing it into the function? Or In the template literal somehow?

我会这样写:

const renderNavItem = ({folder, title, navTitle}) => `<li>
<a href="${folder}/${title}.html">${navTitle}</a>
<li>`;

const renderNav = (items) => `<nav>
${items.map(renderNavItem).join("\n")}
</nav>`;

你也可以写一个小 helper 来解决这个问题:

//"Rules" to convert any value into a string
const string = value => Array.isArray(value) ?
value.map(string).join("") :
value == null || value === false ?
"" :
String(value);

//a formatter that applies these "rules" to the values in a template string
const format = (strings, ...values) => strings.reduce((result, tpl, index) => result + string(values[index-1]) + tpl);

let example = format `here comes the Array:
<ul>${ [1,2,3,4,5].map(v => v&1? `<li>${v}</li>`: v*2) }</ul>
some more text ${1 < 2 && 'conditional text'} rest`;

console.log(example);
.as-console-wrapper{top:0;max-height:100%!important}

显然,您不应该将此示例作为如何构建此类模板的示例,而应该尝试使用模板字符串和标记函数的可能性

关于javascript - 映射到 json 并使用 javascript 转换为 html 时得到额外的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com