如何打破打字稿中的ForEach循环

2022-09-04 00:00:00 break foreach javascript angular typescript

我有以下代码,在某些情况下无法中断循环。

 isVoteTally(): boolean {


 let count = false;
    this.tab.committee.ratings.forEach(element => {

      const _fo = this.isEmptyOrNull(element.ratings.finalOutcome.finaloutlook);
      const _foreign = this.isEmptyOrNull(element.ratings.finalOutcome.foreign);
      const _local = this.isEmptyOrNull(element.ratings.finalOutcome.local);
      const _tally = element.ratings.finalOutcome.voteTally.maj + element.ratings.finalOutcome.voteTally.dis;

      if (_fo == false && _foreign == false && _local == false) {
        if (_tally > 0) {
          **return count = false;**
        }
      } else {
        if (_tally < 0) {
          **return count = false;**
        }
      }
    });
    return count;
  }

在带星号的区域,我希望中断代码并返回布尔值,但我现在无法这样做。有人能帮我吗?

提前谢谢。


解决方案

无法正常脱离forEach()

或者您可以使用Array.every(),因为您希望在中断循环时返回false

如果要返回True,则可以使用Array.some()

this.tab.committee.ratings.every(element => {

  const _fo = this.isEmptyOrNull(element.ratings.finalOutcome.finaloutlook);
  const _foreign = this.isEmptyOrNull(element.ratings.finalOutcome.foreign);
  const _local = this.isEmptyOrNull(element.ratings.finalOutcome.local);
  const _tally = element.ratings.finalOutcome.voteTally.maj + element.ratings.finalOutcome.voteTally.dis;

  if (_fo == false && _foreign == false && _local == false) {
    if (_tally > 0) {
      **return count = false;**
    }
  } else {
    if (_tally < 0) {
      **return count = false;**
    }
  }
});

相关文章