簡體   English   中英

僅在forEach循環的最后一次迭代中觸發函數

[英]Only trigger a function in the last iteration of a forEach loop

以下代碼檢查字段是否為文件類型,以及其中是否有實際文件。 如果是這種情況,請上傳照片並更新建築物。 如果不是這種情況,請使用舊照片更新建築物:

  fields.forEach(field => {
    building[field.name] = field.value || this.building[field.name]
    if (field.type === 'file' && !util.isEmpty(field.photo.file)) {
      api.uploadPhoto(field.photo.file).then(resp => {
        building[field.name] = resp
        this.updateBuilding(building)
      })
    } else {
      building.logo = this.building.logo // to prevent updating logo
      building.floorplan = this.building.floorplan // to prevent updating logo
      this.updateBuilding(building)
    }
  })

它運行良好,但是由於this.updateBuilding(building)處於循環中,因此被稱為倍數。

如何做到這一點,使其僅在上一次迭代中被調用?

您可以檢查fields.lengths 字段數組 ,它將是fields數組的最后一個元素。

if(fields[fields.length - 1]){
 // Loop control will enter in this block in last iteration
 // Enter your update code inside this
}

希望這就是您想要的。

MDN documentation建議對forEach的回調具有三個參數:

  1. 元素值
  2. 元素索引
  3. 遍歷數組

您可以使用它來檢查當前元素的索引是否等於數組的最后一個索引:

fields.forEach((field, index, array) => {

  // YOUR CODE

  if (index === array.length - 1) {
    // DO SOMETHING
  }
});

在每次迭代中使用帶有增量的count變量,如果field.length等於count變量,則使用if條件調用該函數

var count = 0;
var fields_length = fields.length;
fields.forEach(field => {
    building[field.name] = field.value || this.building[field.name]
    if (field.type === 'file' && !util.isEmpty(field.photo.file)) {
      api.uploadPhoto(field.photo.file).then(resp => {
        building[field.name] = resp

      })
    } else {
      building.logo = this.building.logo // to prevent updating logo
      building.floorplan = this.building.floorplan // to prevent updating logo

    }
    if(count == fields_length){
       this.updateBuilding(building)
    }

count++
  })

嘗試:

var len = fields.length;
var counter = 0;

fields.forEach(field => {
    building[field.name] = field.value || this.building[field.name]
    if (field.type === 'file' && !util.isEmpty(field.photo.file)) {
        api.uploadPhoto(field.photo.file).then(resp => {
            building[field.name] = resp

            /* checking if it's the last loop */
            if(counter == len - 1)
                this.updateBuilding(building)
        })
    } else {
        building.logo = this.building.logo // to prevent updating logo
        building.floorplan = this.building.floorplan // to prevent updating logo
  this.updateBuilding(building)
    }

    counter = counter + 1;
})

如何創建一些變量以在循環中保存適當的值; 循環之后,您可以使用這些變量在構建時運行更新。

更新

哦,您實際上需要更新的回調。 您在循環中進行了一些異步操作???

暫無
暫無

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

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