早期退出forEach中的功能?

时间:2017-04-03 08:26:24

标签: javascript arrays foreach

如何提早退出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'

'结束'不能打印。

非常感谢。

3 个答案:

答案 0 :(得分:3)

另一种方法,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;
}

答案 1 :(得分:1)

尝试使用此代替forEach

.every()(第一次迭代器返回false或者假的时候停止循环)

使用every():

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;
}  

答案 2 :(得分:1)

你也不能打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