如何在Javascript中退出函数内部的循环

时间:2018-11-28 11:59:03

标签: javascript function for-loop return break

我正在尝试找到一个值时退出函数调用,而我对此一无所知。

使用调试器,我注意到return found;行使执行跳转到函数的末尾,好吧……但是在for循环中又开始了另一个迭代。

我也尝试使用break。

我的代码在下面。

已编辑

我已经检查了调试器上的逻辑,在found = true上添加了一个断点,它可以正常工作,因此剩下的唯一事情是它应该在此之后正确退出...

//  Tree traversal until answer found via answer.id

    function locateAnswer(wholeTree, answerID) {
      var found = false;
      if (wholeTree.answers) { // checks if next_queston is populated first

        for (var i = 0; i < wholeTree.answers.length; ++i) {        
          if (wholeTree.answers[i].id == answerID) {

            console.log("found!");
            found = true;
            return found;       // TRIED break; TOO

          } else {
            for (var j = 0; j < $scope.breadcrumbs.length; ++j) {
              if ($scope.breadcrumbs[j].question == wholeTree.question) {
                // if already exist, we pop elements until it does not exist anymore
                while ($scope.breadcrumbs[j]) {
                  $scope.breadcrumbs.pop();
                }
              }
            }

            // we push the new breadcrumb
            $scope.breadcrumbs.push({ "question": wholeTree.question, "answer": wholeTree.answers[i].answer });

            locateAnswer(wholeTree.answers[i].next_question, answerID);
          }
        }
      }
     //  ALSO TRIED return HERE AFTER break
    };

2 个答案:

答案 0 :(得分:1)

您应该在循环内部使用break,并在函数末尾返回语句。请更新代码

function locateAnswer(wholeTree, answerID) {
      var found = false;
      if (wholeTree.answers) { // checks if next_queston is populated first

        for (var i = 0; i < wholeTree.answers.length; ++i) {        
          if (wholeTree.answers[i].id == answerID) {

            console.log("found!");
            var found = true;

          break;        // TRIED break; TOO

          } else {
            for (var j = 0; j < $scope.breadcrumbs.length; ++j) {
              if ($scope.breadcrumbs[j].question == wholeTree.question) {
                // if already exist, we pop elements until it does not exist anymore
                while ($scope.breadcrumbs[j]) {
                  $scope.breadcrumbs.pop();
                }
              }
            }

            // we push the new breadcrumb
            $scope.breadcrumbs.push({ "question": wholeTree.question, "answer": wholeTree.answers[i].answer });

            locateAnswer(wholeTree.answers[i].next_question, answerID);
          }
        }
      }
     //  ALSO TRIED return HERE AFTER break
 return found;
    };

答案 1 :(得分:0)

尝试使用break而不是在for循环内返回