Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Checking if all values in an array are not Null - Array / Each /

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!

like image 786
Ash Pettit Avatar asked Mar 09 '16 15:03

Ash Pettit


1 Answers

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; }));
like image 140
Nathan Friend Avatar answered Sep 28 '22 16:09

Nathan Friend