2

Is there any maximum limit of conditions for If in Javascript? I am using following method to detect bombs in division "b". But it skips more than 3 or 4 conditions and hence less bombcount than the actual count.

The following function triggers as soon as I click on div b where b = some number . It has a Kwhere I check for bomb in every cell and if the cell with the bomb satisfies the position criterion it increases bombcount by 1.

    var i = 1;
    var p1 = b-1;
    var p2 = b+1;
    var p3 = b+6;
    var p4 = b-6;
    var p5 = b-5;
    var p6 = b+5;
    var p7 = b-7;
    var p8 = b+7;
    var bombcount = 0;

    while(i<37)
    {
        var check = document.getElementById(i).value;
        if (check == "explode" && b>6 && b<31) {
            if(i==p1 || i==p2 || i==p3 || i==p4 ||
               i==p5 || i==p6 || i==p7 || i==p8) {

               bombcount++
            };
        }
        i++;
    }
4

3 回答 3

4

使用数组 forp和 indexOf 检查是否i在数组中:

var p = [b - 1, b + 1, b + 6, b - 6, b + 5, b - 5, b + 7, b - 7];
if (p.indexOf(i) !== -1) {
    bombcount++;
} 
于 2013-04-18T10:48:54.963 回答
3

if-else不,语句的数量没有限制,无论是一个接一个还是嵌套的 if-else 循环。此外,在 if 语句下可以拥有的条件数量没有限制。

但是,最好switch在这些情况下使用。它提高了可读性和性能。

有关开关语法,请参阅此 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch

要在一系列值上使用 switch,请参阅上一篇文章 Switch statement for greater-than/less-than

于 2013-04-18T10:45:44.980 回答
1

没有限制。作为提示,您最好在switch以下情况下使用和失败:

 switch (i)  {
     case p1:
     case p2:
     case p3:
             // your logic
             break;

 }

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch

于 2013-04-18T10:46:55.440 回答