使用不带花括号的箭头功能,可以将对象中的数据完美呈现到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
}
答案 0 :(得分: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
}
答案 1 :(得分: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
}
答案 2 :(得分:1)
箭头功能缺少花括号,表示返回评估。
如此
matchArray.map(place =>
place.state
)
// is equal to
matchArray.map(place => {
return place.state
})
我建议深入研究es6箭头功能以更好地理解。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions