javascript - 如果在foreach中

标签 javascript angular

我有一个数组 arr=[{key: 'first'},{key: 'second'} ...],我想遍历该数组并检查元素是否具有一个特定的键存在并做一些事情。

  arr.forEach(element => {
     if(element.key === 'first') {
        // do something
     } else { 
        // do something else
     }

     if(element.key === 'second') {
        // do something
     } else { 
        // do something else
     }         
  });

问题是,当它遍历数组时,它首先看到 'first' 然后它遍历 if() 语句,但它也遍历 'second' 项的 else() 语句,因为它没有找到它,当 foreach 遍历数组中的其他项时也是如此。我不知道如何让它一次遍历数组并适本地设置 if() else()。因此,当它找到 'first' 时,我希望它只执行该项目的 if() 而不是其他项目的 else() 。我希望你明白。提前致谢!

编辑:我在这段代码背后的逻辑是,当我调用数据库并找到该数组时,如果该数组中没有 'firstExercise',那么它应该将它添加到该数据库(我正在使用firebase 所以在 else() 我调用 db 来创建那个练习),如果数组中有 'firstExercise' 什么也不做。很抱歉没有澄清这一点。

Edit2:这是我的原始代码:

  res.forEach(element => {
     if (this.numbOfFinished === 1) {
       if (element.key === 'firstExercise') {
           console.log('has')            
      } else {
        awardName = 'firstExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'firstExercise';
         this.awarded = true;
         });
       }
     }
   });


     if (this.numbOfFinished === 5) {
       if (element.key === 'fifthExercise') {
           console.log('has')            
      } else {
        awardName = 'fifthExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'fifthExercise';
         this.awarded = true;
         });
       }
     }
   });

最佳答案

我个人喜欢创建数组来建立键和函数之间的关系。所以我可以迭代并调用正确的。

在这个解决方案中,我喜欢这个解决方案而不是使用 switch/caseif/else 森林,因为你可以应用自动处理,而且你可以很容易地做到进化。

const mapKeyFunc = [{
  key: 'first',

  func: async(x) => {
    console.log('Do something for key first');

    // here you can perform an async request and modify `this`
  },
}, {
  key: 'second',

  func: async(x) => {
    console.log('Do something for key second');

    // here you can perform an async request and modify `this`
  },
}];

const doStuff = async(arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    const mapElement = mapKeyFunc.find(x => x.key === arr[i].key);

    await mapElement.func.call(this, arr[i]);
  }
};

const arr = [{
  key: 'first',
  otherStuff: 0,
}, {
  key: 'second',
  otherStuff: 42,
}];

doStuff(arr).then(() => {}).catch(e => console.log(e));


如果不需要处理是同步的,这里我们有一个异步的方法

const mapKeyFunc = [{
  key: 'first',

  func: async(x) => {
    console.log('Do something for key first');

    // here you can perform an async request and modify `this`
  },
}, {
  key: 'second',

  func: async(x) => {
    console.log('Do something for key second');

    // here you can perform an async request and modify `this`
  },
}];

const doStuff = async(arr) => {
  await Promise.all(arr.map(x => mapKeyFunc.find(y => y.key === x.key).func.call(this, x)));
};

const arr = [{
  key: 'first',
  otherStuff: 0,
}, {
  key: 'second',
  otherStuff: 42,
}];

doStuff(arr).then(() => {}).catch(e => console.log(e));

关于javascript - 如果在foreach中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528628/

相关文章:

javascript - 为什么这个绑定(bind)的 knockout 元素变得未定义?

javascript - 函数变量的值在返回后变得未定义

javascript - 使用 jQuery 更改 html 目录属性

javascript - 如何在javascript中获取对象数组(键值对)的值?

angular - 使用 primeng 日历将样式应用于特定日期

javascript - Angular 6 - jsPDF -autotable - PDF 未正确生成

javascript - Angular:将输入数字限制为两位小数的更好方法?

javascript - 如何在数组中搜索多个可能的匹配项

javascript - [ng-bootstrap] : Passing function to a modal threw a service

javascript - 在 Angular 4 中实现 d3.js