当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Why is the 'o' is true? Javascript(Angular)

问题描述:

Help me please, I'm trying to make a rule for the little game and there is the problem.

I'm creating winning combination and say if the cell && cell+1 && cell+2 == to 'X' then you win, but when between two "X"s presents "o" it also says that "X" wins. Why? Please see my code and the game example on link a the bottom.

this.rezult = function(){

this.arr2.forEach(function(arr, i, innerArr){

arr.forEach(function(val, j){

var wincomb = innerArr[i][j] && innerArr[i][j+1] && innerArr[i][j+2];

var wincomb2 = innerArr[i][j] && innerArr[i+1][j] && innerArr[i+2][j];

var wincomb3 = innerArr[i][j] && innerArr[i+1][j+1] && innerArr[i+2][j+2];

console.log(wincomb == "X" && innerArr[i][j] !== "o");

// console.log(innerArr);

// THE RULE

if(wincomb == "X"){

alert(' X wins!');

}

});

});

};

Link to JSFiddle

网友答案:

In JavaScript, the && operator has interesting behavior with non-boolean values.
If the left-side of && is "truthy", the result is the right-side.
If the left-side of && is "falsey", the result is the left-side.

All non-empty strings are "truthy".

So, consider these examples:

("A" && "B" && "C") === "C"
("" && "B" && "C") === ""
(0 && "B" && "C") === 0
("X" && "X" && "O") === "O"
("O" && "O" && "X") === "X"

By the looks of it, you're trying to check if all 3 values are equal. You shouldn't use && for that, you should use === for that.

At the risk of doing your homework for you ;) here's a good way to do this:

function areTheSame(a,b,c) {
    return a === b && b === c;
}
var down = areTheSame(innerArr[i][j], innerArr[i][j+1], innerArr[i][j+2]);
var across = areTheSame(innerArr[i][j], innerArr[i+1][j], innerArr[i+2][j]);
var diagonal = areTheSame(innerArr[i][j], innerArr[i+1][j+1], innerArr[i+2][j+2]);

if (down || across || diagonal) {
    var winner = innerArr[i][j];
    alert( winner + " wins!");
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: