【问题标题】:How to make for each loop stop at first true condition如何使每个循环在第一个真实条件下停止
【发布时间】:2018-01-20 10:27:25
【问题描述】:

我正在将登录/注册表单作为一个小型个人项目制作,但遇到了一个小问题。

所有新用户都存储在本地存储中。
当用户登录时,我想从本地存储中检索所有用户并循环访问它们以查看登录详细信息是否与用户注册详细信息匹配。

我基本上已经创建了代码,只是无法让if/else 语句正常工作。如果值为true,则返回true,但继续循环并为不是true 的值返回false

如何让循环在第一个 true 值处停止?

这是我的代码:

// gather information and loop through users array
document.querySelector("#login").addEventListener("click", function(e)
{
    // login details gathered from user
    var logId = document.getElementById("logId").value;
    var logPass = document.getElementById("logPass").value;
    // get all the users from local stroage and loop through
    var allUsers = JSON.parse(localStorage.getItem("users"));
    allUsers.forEach(function(user) {
        if (user.userId === logId && user.userPassword === logPass) {
            console.log("true");
        } else {
            console.log("fasle");
        }
    });
    // prevent form from submitting
    e.preventDefault();
});

【问题讨论】:

  • return 有什么问题?
  • @AyushGupta return in forEach work like continue in for ,检查我的答案 soulotion 是 try-catch

标签: javascript arrays for-loop


【解决方案1】:

我建议使用.somehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

如果有任何用户符合您的要求,则返回 true,否则返回 false

   let isUserMatched = allUsers.some(function(user) {
       return user.userId === logId && user.userPassword === logPass)
    });
   if(isUserMatched){
     // do something
   }

【讨论】:

  • 我很高兴它帮助了你。请接受答案,以便对其他人也有帮助。
【解决方案2】:

使用普通的for循环(不是foreach)并使用break;当条件为真时退出for循环

【讨论】:

    【解决方案3】:

    根据 MDN 文档:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    没有办法停止或中断 forEach() 循环,只能通过 抛出异常。如果你需要这样的行为,forEach() 方法 是错误的工具。使用普通循环或 for...of 代替。如果你是 测试谓词的数组元素并需要布尔返回 值,您可以使用 every() 或 some() 代替。如果有的话,新的 方法 find() 或 findIndex() 可用于提前终止 真正的谓词也是如此。

    另外,你也可以做的是

    var currentUser = allUsers.find(function fn(user) {
      return user.userId === logId && user.userPassword === logPass;
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案4】:

      没有简单的方法来短路forEach,你可以做的是使用像这样的传统for循环

      // gather information and loop through users array
      document.querySelector("#login").addEventListener("click", function(e) {
          // login details gathered from user
          var logId = document.getElementById("logId").value;
          var logPass = document.getElementById("logPass").value;
          // get all the users from local stroage and loop through
      
          var allUsers = JSON.parse(localStorage.getItem("users"));
          for (var i = 0; i < allUsers.length; i++) {
              if(user.userId === logId && user.userPassword === logPass){
                  console.log("true");
                  break;
              } else {
                  console.log("false");
              }
          }
         // prevent form from submitting
         e.preventDefault();
      });
      

      【讨论】:

        【解决方案5】:

        你可以使用 try-catch 来停止 forEach ,我写了一个示例代码,你可以随意更改

        var q = [1,2,3,4,5,6,7,8,9,10]
        try
            {
                q.forEach(function (x){
                    print(x)
                    if (x==3)
                    throw "bye bye"
        
                })
        
            }
        catch(e)
            {
                print(e)
            }
        

        【讨论】:

          【解决方案6】:

          forEach 并不是一个真正的声明。它只是一个function,它在其参数中调用传递的function。因此,在其 for 语句中处理某些内容是完全不可能的。
          此时我建议您使用for 语句并从数组中选择索引:

          for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length; i++, user = allUsers[i]) {
              //Here's user that is the same such than the parameter in your function.
          }
          

          现在您可以添加条件链接“直到”。让我们考虑变量condition

          var condition = false;
          for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length && !condition; i++, user = allUsers[i]) {
              //When condition is true, the condition of the for statement gets false and the for cycle stops.
          }
          

          或者:

          var condition = false;
          for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length; i++, user = allUsers[i]) {
              if (condition)
                  break;
              //When condition is true, the above if statement is passed and for cycle is breaked.
          }
          

          你也可以创建自己的forEach函数:

          //In this example I overwrite the normal forEach function
          Array.prototype.forEach = function(callback) {
              window.$break = function() {
                  window._break = true;
              };
              window.$continue = function() {
                  window._continue = true;
              };
              for (let l = this.length, i = 0, e = this[i]; i < l; i++, e = this[i]) {
                  if (window._break) {
                      window._break = false;
                      break;
                  }
                  if (window._continue) {
                      window._continue = false;
                      continue;
                  }
                  callback(e, i);
              }
          };
          

          现在您必须将函数$break()function 中的return 语句结合起来:

          var condition = false;
          allUsers.forEach(function(user) {
              if (condition) {
                  $break();
                  return;
              }
          });
          

          后面我贴的解决方案,我也写在this fiddle

          【讨论】:

            【解决方案7】:

            只需使用普通的for(或some),foreach 只是在每个元素上调用传递的函数,无法中断。

            【讨论】:

              猜你喜欢
              • 2019-10-17
              • 2015-09-13
              • 1970-01-01
              • 2016-03-18
              • 2021-09-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多