只在forEach循环的最后一次迭代中触发函数
Only trigger a function in the last iteration of a forEach loop
下面的代码检查字段是否为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
的回调有三个参数:
- 元素值
- 元素索引
- 正在遍历的数组
你可以用它来检查当前元素的索引是否等于数组的最后一个索引:
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++
})
相关文章:
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 如何迭代Array.prototype函数
- Map函数没有't迭代所有子项
- 在HTML集合上迭代,以便在构造函数中动态定义值
- 如何在 JavaScript 中动态地编写可迭代的函数数组
- 函数崩溃,因为太多迭代jQuery
- DOM:如何根据迭代器值设置元素宽度并在mouseover上调用函数
- 迭代node.js请求函数
- 如何将这个递归函数转换为迭代函数
- 如何验证for循环是否完成了node js中的所有迭代,循环是否包含带回调的函数调用
- 创建自定义迭代“;每个“;函数
- 通过函数(动画)每次重新迭代时重置画布笔划.怎样
- 在jquery each()迭代器函数中访问JS对象
- jQuery使用不同的参数多次迭代函数
- node.js for循环在函数调用返回之前进行迭代,从而产生对象问题
- 迭代中的异步函数 - javascript
- 使用jquery的每个函数迭代父li
- 函数迭代日期数组会产生意想不到的结果
- Node.js中使用异步瀑布的函数迭代
- JS函数迭代对象并只打印特定键的值返回undefined