JavaScript if if语句有3个条件

时间:2013-11-24 07:08:08

标签: javascript jquery

我不知道为什么这不起作用,但我想可能是因为声明,或者testRedtestGreen功能相互冲突。如果是这样,请你建议一个更好的方法。 代码:

var greenSoldier = 5;
var redSoldier = 5;
var territory = ['green', 'green', 'neutral', 'neutral', 'green', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral', 'red', 'neutral', 'neutral', 'red', 'red'];
var soldier = [4, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 4];
var turn = 'green';

function testGreen(itemNumber, soldiers, itemName) {
    if (greenSoldier > 0 && territory[itemNumber] == 'green') {
        var unchanged = soldier[itemNumber];
        var changed = unchanged + 1;
        soldier[itemNumber] = changed;
        $(itemName).html(soldier[itemNumber]);
        greenSoldier -= 1;
        console.log(greenSoldier);
    } else if (greenSoldier > 0 && territory[itemNumber == 'neutral'] && turn == 'green') {
        soldier[itemNumber] += 1;
        console.log(soldier[itemNumber]);
        $(itemName).html(soldier[itemNumber]);
        greenSoldier -= 1;
        console.log(greenSoldier);
    }
}

function testRed(itemNumber, soldiers, itemName) {
    if (redSoldier > 0 && territory[itemNumber] == 'red') {
        var unchanged = soldier[itemNumber];
        var changed = unchanged + 1;
        soldier[itemNumber] = changed;
        $(itemName).html(soldier[itemNumber]);
        redSoldier -= 1;
        console.log(redSoldier);
    } else if (redSoldier > 0 && territory[itemNumber == 'neutral'] && turn == 'red') {
        soldier[itemNumber] += 1;
        $(itemName).html(soldier[itemNumber]);
        redSoldier -= 1;
        console.log(redSoldier);
    }
}
$('#item4').click(

function () {
    testGreen(3, soldier[3], '#item4');
    testRed(3, soldier[3], '#item4');
})

3 个答案:

答案 0 :(得分:3)

尝试在代码中出现territory[itemNumber] == 'neutral'代替territory[itemNumber == 'neutral']

答案 1 :(得分:1)

else if (redSoldier > 0 && territory[itemNumber == 'neutral'] && turn == 'red')

你搞砸了你的阵列访问。

else if (redSoldier > 0 && territory[itemNumber] == 'neutral' && turn == 'red')

答案 2 :(得分:0)

确保您的jquery已正确安装。在javaScript中,您可以通过以下方式声明数组:

  

var soldier = new Array(4,2,0,0,2,0,0,0,0,0,0,0,0,0,2,4);

然后在testGreen / testRed函数上,尝试将士兵参数视为数组:

  

function testRed(itemNumber,soldiers,itemName)

     

{

     
    

//在这里行动。

  
     

}