javascript - In the for traversal loop, how to make the result alert after else pop up only once?
黄舟
黄舟 2017-05-19 10:40:28
0
3
1055

In a for loop, when the previous two if conditions are not met, the alert prompt box will pop up. Due to the traversal query, alert will pop up multiple times according to the number of arrays. Please tell me how to truncate this so that it only pops up once after judgment?

$(function(){
    var jsons = [
            {"id":"621234","info":"内容一"},
            {"id":"62123456","info":"内容二"},
            {"id":"624321","info":"内容三"},
    ]

    function f(jsons,num) {
        var num8 = num.substr(0,8);
        var num6 = num.substr(0,6);
        var result6 = '';
        var result8 = '';
          for(var i = 0,len = jsons.length; i < len;i++) {
              var id = jsons[i].id;
              if(id == num8) {
                  result8 = jsons[i].info.toString();
                  $("#card_info").fadeIn("500");
                  $("#close").fadeIn("500");
                  break;
              }
              if(id == num6) {
                  result6 = jsons[i].info.toString();
                  $("#card_info").fadeIn("500");
                  $("#close").fadeIn("500");
              }
              else{
                alert("不符合条件");
              }
           }
          return result8 ? result8 : result6;
    }

    $("#down").click(function(){
      var user_info = $("#txt").val();
      var table = document.getElementById("card_info");
      table.innerHTML=(f(jsons, user_info));
    })

});

Currently, the pop-up window will pop up three times according to the number of json data. . .

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
Peter_Zhu
function f(jsons, num) {
    var num8 = num.substr(0, 8);
    var num6 = num.substr(0, 6);
    var result = '';
    var inArr = 0;
    for (var i = 0, len = jsons.length; i < len; i++) {
        var id = jsons[i].id;
        if (id == num8) {
            result8 = jsons[i].info.toString();
            $("#card_info").fadeIn("500");
            $("#close").fadeIn("500");
            inArr++;
            break;
        }
        if (id == num6) {
            result6 = jsons[i].info.toString();
            $("#card_info").fadeIn("500");
            $("#close").fadeIn("500");
            inArr++;
        }
    }
    !inArr && alert("不符合条件");
    return result8 ? result8 : result6;
}
黄舟

else if()

洪涛

Place it outside the for loop, and the alert will only occur when the values ​​of result8 and result6 are both empty.
Why not break when id==6;?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template