javascript - 提前退出 forEach 中的函数?

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

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

'its true'

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

its true

its true

the end

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

我并不是试图退出 forEach,而是结束 foreach 中的“checkIfFollowed”方法。

不应打印“the end”。

最佳答案

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

关于javascript - 提前退出 forEach 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43179830/

相关文章:

javascript - 如何检查一个对象是否为空? [javascript]

javascript - 如何创建动态加载的页面 URL?

javascript - 使 div 的大小和位置与视频的大小和位置相同

c# - c++ 结构指针转换为数组互操作 c#

php - 如何在 PHP、MySQL 中的 foreach 中使用 array_intersect

javascript - 使用 vanilla javascript 添加与类名匹配的增量数据属性

c# - Foreach循环检查空字符串并为其赋值c#

javascript - 为什么我在提交表单时收到 500 错误?

ios - 可以将类型 '__NSArray0' 的值转换为 'CIRectangleFeature'

javascript - 我的递归函数哪里出错了?