簡體   English   中英

如果語句未執行正確的代碼?

[英]If statement not executing correct code?

因此,我嘗試開發一個Tic Tac Toe游戲,以使用javascript進行練習,但遇到了障礙。 我有一個if語句,應該返回true,但不是。 這是一個樣本。

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) {
                   ^^

乍看之下,您有兩個問題。

首先, event未定義。 將其定義為.click調用中的函數參數。

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

其次,正如Pointy所說, =是分配, =====是為了比較。 從而

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

需要是

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

關於=====之間的區別,您可以在此處獲取更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

簡短的版本,最好使用===除非您完全確定自己知道自己在做什么,並想顯式使用==

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM