JS - 模板文字出乎意料,

时间:2018-03-18 11:17:26

标签: 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()
}

以HTML格式输出

Username: Thor 
1002023

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

,
Username: Superman 
5948393

,
Username: Spiderman 
5949384

只是奖金

解释为什么会发生这种情况来自T.J.克劳德是正确的,他建议我应该使用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 个答案:

答案 0 :(得分:5)

因为map返回一个数组,然后${...}将其强制转换为字符串,后者使用Array#join,默认使用,作为元素之间的分隔符。您可以通过在.join("")电话的结尾添加map来解决此问题:

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