在我的一个 WordPress 项目中,我必须发布一个 get 请求并在前端呈现响应数据。为了呈现数据,我尝试使用 forEach() 循环,但它总是显示未定义,但如果我使用 map(),同样的事情也能正常工作。 现在我只想知道 forEach() 有什么问题。我在下面给出了工作和不工作的代码:
不工作:
getResults() {
$.getJSON(`http://localhost/from_wp_course/wp-json/wp/v2/posts?search=${this.searchField.val()}`, posts => {
this.resultsDiv.html(`
<h2 class="search-overlay__section-title">General Information</h2>
<ul class="link-list min-list">
${posts.forEach(item => `<li><a href="${item.link}">${item.title.rendered}</a></li>`)}
</ul>
`);
});
}
工作:
getResults() {
$.getJSON(`http://localhost/from_wp_course/wp-json/wp/v2/posts?search=${this.searchField.val()}`, posts => {
this.resultsDiv.html(`
<h2 class="search-overlay__section-title">General Information</h2>
<ul class="link-list min-list">
${posts.map(item => `<li><a href="${item.link}">${item.title.rendered}</a></li>`).join('')}
</ul>
`);
});
}
答案 0 :(得分:0)
.foeEach
返回值未定义(为什么你得到未定义)但 .map
返回一个新数组。