簡體   English   中英

無法在函數內部編輯全局變量

[英]Can't Edit Global Variable Inside Function

我先聲明全局變量str ,然后在一個函數內對其進行編輯,然后嘗試在該函數內對其進行調用。 但是,在調用時,它將返回初始的全局值''

 var str = ''; function getProjects(service) { //find all projects fetch(`http://localhost:8888/wp-json/wp/v2/projects?_embed`) // get the response as JSON .then(r => r.json()) // go through the posts and append each posts' title to the HTML element .then(projects => { //for each project, find categories projects.forEach(project => { // find categories of each project project.categories.forEach(category => { // check if category name is equal to a service name fetch(`http://localhost:8888/wp-json/wp/v2/categories/${category}`) .then(r => r.json()) .then(response => { if(serviceData[service].slug == response.slug) { // if previous evaluates to true, add project to service if(project._embedded['wp:featuredmedia']) { str += `<div class='project-div'><a href='#'><img src='${project._embedded['wp:featuredmedia'][0].media_details.sizes.medium.source_url}' /><div class='bottom-text'>${project.title.rendered}</div></a></div>`; } } }) }) }) }) .then(() => { document.getElementById('projects-container').innerHTML = str; }) } 

在第二個then()處理函數中,返回str並將其作為第三個then()處理函數的參數接受,如下所示

              if(project._embedded['wp:featuredmedia']) {
                //...
                return str;
              }
            }
          })
      })
    })

  })
  .then((str) => {
    document.getElementById('projects-container').innerHTML = str;
  })

您應該使用常規的for循環,而不是forEach。 數組原型的本機高階函數與承諾函數不兼容。 嘗試將其更改為for循環,看看是否可以解決您的問題。

另外,為了演示forEach如何破壞代碼,請在追加到字符串之后立即添加控制台日志,然后在使用該已編輯字符串之前立即添加控制台日志。 您很可能會看到后一個控制台日志發生在forEach中的日志之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM