【问题标题】:How to solve this forEach loop problem in wp?如何在 wp 中解决这个 forEach 循环问题?
【发布时间】:2021-04-02 20:18:03
【问题描述】:

在我的一个 WordPress 项目中,我不得不发布一个获取请求并在前端呈现响应数据。为了呈现数据,我尝试使用 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>
      `);
    });
  }

【问题讨论】:

    标签: wordpress foreach


    【解决方案1】:

    .foeEach 返回值未定义(为什么会得到未定义),但 .map 返回一个新数组。

    【讨论】:

    • 能否详细说明一下?
    猜你喜欢
    • 2019-02-23
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    相关资源
    最近更新 更多