简体   繁体   中英

If statement not executing correct code?

So I am trying to develop a Tic Tac Toe game for practice with javascript but I've hit a roadblock. I have an if statement that should be returning true but it isn't. Here is a sample.

var game = true;
var x = 'X';
var o = 'O';
var blank = '';

var turn = x;
var board = [blank, blank, blank,
             blank, blank, blank,
             blank, blank, blank];

function write() {

    $('td').click(function() {
        //Making sure that the block that was clicked can only be clicked once
        var id = $(event.target).attr('id');
        var digit = parseInt(id.slice(-1));
        //check to see of the block has been clicked on
        if (board[digit] = blank) {
            board[digit] = turn;
            $(board[digit]).html(turn.toUpperCase());
            if (turn = x) {
                turn = o;
            } else if (turn = o) {
                turn = x;
            }

        } else {
            alert("That box has already been clicked on!")
        }
    }); 

}
 if (board[digit] === blank) {
                   ^^

You have two issues at first glance.

First, event is undefined. Define it as a function parameter in your .click call.

 $('td').click(function(event) { /* rest of the code */ }

Second, as Pointy commented, = is for assignment, == and === are meant for comparisons. Thus

if (board[digit] = blank) { /**/ }

needs to be

if (board[digit] === blank) { /**/ }

Regarding the difference between == and === you can get more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Short version, prefer === unless you're absolutely sure you know what you're doing and want to explicitly use == .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM