JS - 模板文字出乎意料,

Bjö*_*rth 3 javascript template-literals

所以我只是用模板文字练习一点,,我的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()
}
Run Code Online (Sandbox Code Playgroud)

以HTML格式输出

Username: Thor 
1002023

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

,
Username: Superman 
5948393

,
Username: Spiderman 
5949384
Run Code Online (Sandbox Code Playgroud)

只是奖金

解释为什么从TJ 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>`)}`
}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

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

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