13

Working on TicTacToe in JavaScript/JQuery. Beginner programmer but couldn't find this online.

At the moment I have a normal array called "game_board". The array has 9 values which are 0-8. It is not a 'hash'.

I'm looking into a loop or similar that checks if all values in array are not null. Should all values in the "game_board" array not be Null then the code should make an action such as [Alert("Draw")]. If any values in the array have a value the function should do nothing.

Here's my code attempt. Any ideas would be aweesome. My attempt is the theory that the loop breaks if it finds a null value. If it does not find a null value it goes to ELSE and reports 'draw'

    // check draw
for (var p = 0; p < 9; p++) { 
    if (game_board[p] === null) {
        break;
    }
    else {
        alert("Draw");
    }
}

Thanks very much. I know this maybe a basic question but appreciate any answers.

Please excuse my newness! Not 100% sure of the logic. Perhaps something with Jquery will help!

2
  • Do you want the alert to happen only if none of the items in the list are null? Commented Mar 9, 2016 at 15:09
  • Yes thanks :). Imagine TicTacToe with 9 squares filled in with no winner :P Commented Mar 9, 2016 at 15:22

1 Answer 1

22

Use Array.some to check if any of the values are null:

var isAtLeastOneNull = game_board.some(function(i) { return i === null; });

Alternatively, use Array.every to do the reverse check:

var areAllNotNull = game_board.every(function(i) { return i !== null; });

Demo:

var game_board = [true, true, true, true, true, true, true, null, true];

document.writeln('There is at least one null item: ' + game_board.some(function(i) { return i === null; }));
document.writeln('<br />');

game_board = [true, true, true, true, true, true, true, true, true];

document.writeln('There is at least one null item: ' + game_board.some(function(i) { return i === null; }));

Sign up to request clarification or add additional context in comments.

5 Comments

This sounds awesome. I'm just trying to get it to work!
I think I must be a goldfish. Or maybe it's too late! Is this how I'd do your solution? var isAtLeastOneNull = game_board.some(function(p) { return p === null; }); if (isAtLeastOneNull = false) { alert("draw") }
That's close - just change (isAtLeastOneNull = false) to (isAtLeastOneNull === false). Or even better, (!isAtLeastOneNull) .
// check draw if (game_board.some(elem => elem === null)) { } else { alert("draw"); } // HUZZAHHH!!
Haha tiny bug but I can fix :P. Now even if you win on the last move it's a draw :P. I'm sure I can fix though lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.