只在forEach循环的最后一次迭代中触发函数

Only trigger a function in the last iteration of a forEach loop

本文关键字:函数 迭代 最后一次 forEach 循环 只在      更新时间:2023-09-26

下面的代码检查字段是否为file类型,以及其中是否存在实际的文件。如果是这样的话,上传照片并更新建筑。如果不是这样,请使用旧照片更新建筑物:

  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)在循环中,它被称为倍数。

如何使它只在最后一次迭代中被调用?

MDN documentation建议对forEach的回调有三个参数:

  1. 元素值
  2. 元素索引
  3. 正在遍历的数组

你可以用它来检查当前元素的索引是否等于数组的最后一个索引:

fields.forEach((field, index, array) => {
  // YOUR CODE
  if (index === array.length - 1) {
    // DO SOMETHING
  }
});

您可以检查字段。字段数组的长度,它将是字段数组的最后一个元素。

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

希望这就是你要找的

尝试:

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;
})

如何创建一些变量来保存循环中的适当值;在循环之后,您可以使用这些变量在构建时运行更新。

哦,你实际上需要一个更新的回调。你在循环中得到了一些异步操作??

在每次迭代中使用带增量的计数变量,并使用if条件if字段。长度等于count变量调用函数

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++
  })