如何在for循环中只执行一次else阻塞?

时间:2017-02-04 19:07:15

标签: javascript if-statement for-loop

在下面的代码片段中if block仅在myCity == cites时显示成功警报,然后中断循环执行。但是在执行之前if block else块将执行每个索引(例如:引用[0],引用[1],引用[2])并显示失败警报,直到块成功为止。

但是我想只为整个执行显示一次失败警报消息,任何人都可以帮助我吗?

    var cites = [ "Bangalore", "Chennai", "Delhi", "Mumbai", "Cochin", "Mysore" ];
    var myCity = "Mumbai";
    for (i = 0; i < cites.length; i++) {
        if (myCity == cites[i]) {
            alert("Success:" + cites[i]);
            break;
        } else {
            alert("Failed:" + cites[i]);
        }
    }

4 个答案:

答案 0 :(得分:3)

我知道你想展示failed,即使有一个成功的项目。因此,存储在另一个数组中失败,然后稍后显示:

&#13;
&#13;
    var cites = [ "Bangalore", "Chennai", "Delhi", "Mumbai", "Cochin", "Mysore" ];
    var failed = [];
    var myCity = "Mumbai";
    for (var i = 0; i < cites.length; i++) {
        if (myCity == cites[i]) {
            alert("Success: " + cites[i]);
        } else {
            failed.push(cites[i]);
        }
    }
    if (failed.length > 0)
    	alert("Failed: " + failed);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用some(请参阅https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/some):

&#13;
&#13;
var cities = [ "Bangalore", "Chennai", "Delhi", "Mumbai", "Cochin", "Mysore" ];
var myCity = "Mumbai";
if (cities.some(function(city){
  return city == myCity
})) {
  alert("Success " + myCity);
} else {
  alert("Failed:" + myCity);
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果找到了结果,您可以使用额外的变量来存储。

&#13;
&#13;
var cites = ["Bangalore", "Chennai", "Delhi", "Mumbai", "Cochin", "Mysore"];
var myCity = "Mumbai";
var found = false;
for (i = 0; i < cites.length; i++) {
  if (myCity == cites[i]) {
    alert("Success:" + cites[i]);
    found = true;
    break;
  }
}

if (!found) {
  alert("Failed");
}
&#13;
&#13;
&#13;

答案 3 :(得分:1)

&#13;
&#13;
var cites = [ "Bangalore", "Chennai", "Delhi", "Mumbai", "Cochin", "Mysore" ],
    myCity = "Mumbai",
    success = false;

for (i = 0; i < cites.length; i++) {
    if (myCity == cites[i]) {
        alert("Success:" + cites[i]);
        success = true;

        break;
    }
}
if (!success) {
    alert("Failed:" + cites[i]);
}
&#13;
&#13;
&#13;

这段代码是正确的。