如何在TypeScript中中断ForEach循环

时间:2018-08-08 12:58:34

标签: angular typescript foreach break

我有一个下面的代码,在某些情况下我无法打破上面的循环。

 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;

}

在星号标记的区域,我想破坏代码并返回布尔值,但是我现在无法执行。有人可以帮我吗?

谢谢。

6 个答案:

答案 0 :(得分:11)

this.tab.committee.ratings.forEach不是运算符。 Typescript允许更具可读性的代码。

使用 for 样式如下:

for(let a of this.tab.committee.ratings) {
   if(something_wrong) break;
}

p.s。忘记了Angular中的“使用jQuery编码”。只是不起作用。

答案 1 :(得分:2)

无法正常脱离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;**
    }
  }
});

答案 2 :(得分:1)

您不能“中断”,它甚至不会运行,因为中断指令在技术上并不处于循环状态。 解? 只需使用普通的for循环即可。没有人会嘲笑你。

答案 3 :(得分:0)

这是为Lodash

forEach(this.diningService.menus, (m: any) => {
      this.category = find(m.categories, (c: any) => {
        return c.id === Number(categoryId);
      });
      if (this.category) { return false; }
    });

答案 4 :(得分:0)

我认为更好的解决方案是使用 for。 使用 for 您可以在找到时返回一个值并中断循环。这是一个更清洁的解决方案

for (element of this.tab.committee.ratings) {
// and here you use your element, when you return a values it stops the cycle

if (element === something){
 return element;
 }
}

答案 5 :(得分:-3)

只需执行return false;。会破裂的。