gpt4 book ai didi

javascript - JS - 模板文字意外,

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:06 25 4
gpt4 key购买 nike

所以我只是用模板文字做了一些实验,我似乎在我的 html 输出中得到了一个意想不到的 ,。任何人都可以向我解释为什么这些 , 在我使用 map 时显示?

 this.highscore = [
{
"username" : "Thor",
"highScore": 1002023
},
{
"username" : "Hulk",
"highScore": 1037465
},
{
"username" : "Superman",
"highScore": 5948393
},
{
"username" : "Spiderman",
"highScore": 5949384
}
]

template() {
return `high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`)}`
}

render() {
this.innerHTML = this.template()
}

以 HTML 格式输出

Username: Thor 
1002023

, /* <----- where does this sucker come from? */
Username: Hulk
1037465

,
Username: Superman
5948393

,
Username: Spiderman
5949384

只是奖金🦄

从 T.J. 解释为什么会发生这种情况。 Crowder 是正确的,他建议我应该使用 join 并且为了好玩,我用自定义函数标记了模板来处理它,将它留在这里咯咯地笑:

function removeYaOldBugger(strings, personExp, ageExp) {
return personExp.join("")
}

template() {
return removeYaOldBugger`high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`)}`
}

最佳答案

因为 map 返回一个数组,然后 ${...} 将它强制转换为字符串,其中使用了 Array#join,这默认使用 , 作为元素之间的分隔符。您可以通过将 .join("") 添加到 map 调用的末尾来修复它:

return `high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`).join("")}`
// >>-------------------------------------------------------------------------------------------------------^^^^^^^^^

关于javascript - JS - 模板文字意外,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347243/

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