箭头函数在没有花括号的情况下运行良好。添加花括号{ return }后,它就出现了问题。

4

我通过使用箭头函数而没有使用花括号,完美地将我的对象数据渲染到DOM中。

当我尝试在同一箭头函数后添加花括号时,DOM不会呈现任何数据。

CODE WORKS WITHOUT CURLY BRACES AFTER ARROW FUNCTION

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => 
        `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    ).join('')
    suggestion.innerHTML = html

}


THE SAME CODE BREAKS WITH CURLY BRACES AFTER ARROW FUNCTION 

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return
        `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 
3个回答

4

你遇到了分号自动插入规则中的“陷阱”。在 return 后,如果表达式不在同一行开始,则会自动添加分号。

如果按照以下方式更改你的函数,它应该可以正常工作:

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 

3
当您使用箭头函数并在return语句之后返回值时,发生的情况如下所示:
return
`My Statement` // unreachable code

你将会收到一个错误提示。但是如果你像这样做的话:
return `My Statement` //reachable code

如果您按照以下方式进行操作,它应该可以解决您的问题:
function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 

1

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