【问题标题】:Early exit from function in a forEach? [duplicate]提前退出 forEach 中的函数? [复制]
【发布时间】:2017-08-28 00:52:21
【问题描述】:

如何提前退出我的 TypeScript 文件中的函数?

checkIfFollowed(){
    
    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');                
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}

当我运行它时,它已完全执行,但它应该在第一次之后退出:

'这是真的'

但在我的控制台中,我得到:

这是真的

这是真的

结束

Foreach 按预期循环了 2 次,但是为什么该方法在点击“返回”后没有停止?

我不是想退出 forEach,而是在 foreach 中结束方法“checkIfFollowed”。

'the end' 不应该被打印出来。

【问题讨论】:

  • 请您发布 currentUserInfos;
  • currentUserInfos.followed中有2个对象,只是嵌套对象,没什么特别的
  • 实际要求是什么?您将此处的 if 检查硬编码为if(18785 == 18785)。我认为这不是您的实际要求。
  • 我想知道如何在任何地方结束一个方法。

标签: javascript arrays foreach


【解决方案1】:

试试这个而不是 forEach

.every() (迭代器第一次返回 false 或某些错误时停止循环)

每个():

checkIfFollowed(){

        this.currentUserInfos.followed.every(function(element, index) {
            // Do something.
            if (18785 == 18785){
                console.log('its true');                
                this.alreadyFollowed = true;
                return false;
            }
        });
        if(this.alreadyFollowed) 
        {
            return ;
        }
        this.alreadyFollowed = false;
        console.log('the end');
        return;
}  

【讨论】:

  • 感谢您的回答。当我尝试这个时,'return' 会中断循环,但不会结束方法。
  • 它返回相同的输出?
  • 现在试试,忘记返回false;
  • 这里方法的迭代不会停止。但是你可以通过if检查来限制某行代码的执行。但我认为最好使用some 而不是forEach
  • .every() (迭代器第一次返回 false 或错误的东西时停止循环)
【解决方案2】:

另一种方法,for 循环:

checkIfFollowed() {
  for (let i = 0; i < this.currentUserInfos.followed.length; ++ i) {
    if (18785 == 18785) {
      console.log('its true');                
      this.alreadyFollowed = true;
      return; // exit checkIfFollowed() here
    }
  }

  this.alreadyFollowed = false;
  console.log('the end');
  return;
}

【讨论】:

  • 它有效。奇怪,为什么它不适用于 forEach 方法?非常感谢。
  • 因为使用 forEach,您正在输入一个新函数 (.foreach(function (e) {…})) 并在那里调用 return 会停止该新函数,而不是父函数 (checkIfFollowed)。不客气!
【解决方案3】:

你也不能打foreach :) 这样做:

checkIfFollowed(){

    const filtered = this.currentUserInfos.followed
       .filter(el => el.id === 18785) // or some other condition
       .forEach(element => {
         // maybe you don't need to do anything here
         // or you can continue processing the element and you know you only have 
         // items that you want
      });

   this.alreadyFollowed = filtered.length > 0;
   console.log('the end');
//    return; // no need for an empty return at the end of a function.
}

HTH

【讨论】:

  • 感谢您的回答。不错的方法,也会试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多