Javascript函数返回意外结果

php*_*ete 2 javascript

我已经编写了大量的Javascript,主要是使用JQuery,但我很难解决一些问题.

在下面的代码中(也在这里找到),我只想twoExists()在某些逻辑中使用函数的布尔返回值.我不知道为什么会发生这种情况,但它直观地起作用.就像在,如果我切换逻辑,我得到我想要的结果.

<html>
    <p>One</p>
    <p>Two</p>
    <p>Three</p>
    <p>Four</p>
    <strong></strong>
</html>

var myJS = {
    twoExists: function() {
       $("p").each(function() {
          if($(this).text() == "Two") {
              return true;
           }
       });

       return false;
    },
    foo: function() {
        if(myJS.twoExists()) {
            $("strong").text("Found two");
        }
        else {
            $("strong").text("Did not find two");
        }
    }

    bar: function() {
        if(! myJS.twoExists()) {
            $("strong").text("Found two");
        }
        else {
            $("strong").text("Did not find two");
        }
     }
}

myJS.foo(); // result: <strong>Did not find two</strong>
myJS.bar(); // result: <strong>Found two</strong>
Run Code Online (Sandbox Code Playgroud)

jhu*_*mel 5

我认为这可能会发生,因为jquery中的每个循环如何返回.return truecontinue普通js循环中的语句一样工作,我认为它不会从twoExists函数返回 - 相反它只是从当前迭代跳转到下一个迭代.也许试试这个:

twoExists: function() {
   var found = false;
   $("p").each(function() {
      if($(this).text() == "Two") {
          found = true;
       }
   });

   return found;
},
Run Code Online (Sandbox Code Playgroud)