JS - 模板字面量出现意外情况

3

我正在使用模板字面量进行测试,但是在输出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>`)}`
}
1个回答

5

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接