user1890615
user1890615

Reputation:

Check if values in array are defined

I'm trying to populate an array with zeros and ones in such a way that if you arrange it into a 6 by 6 grid there will be randomly scattered ones directly adjacent to each other.

for example:
001101
111001
001011
001110
111000

In order to check whether or not there is a one next to a potential one I need to check 4 values of the array. This is where I'm having difficulty. I've tried implementing solutions from other questions on Stackoverflow, but I can't get it to work specifically with this if statement.

function initialize(){
    tile = new Array(6);
    first = true;
    for(i = 0; i < 6; i++){
        tile[i] = new Array(6);
        for(j = 0; j < 6; j++){
            //This is where I'm having difficulty
            if(Math.random() < .75 && tile[i + 1][j + 1] != 'undefined' || tile[i - 1][j - 1] != 'undefined' || tile[i - 1][j + 1] != 'undefined' || tile[i + 1][j - 1] != 'undefined' || first){
                tile[i][j] = 1;
                first = false;
            }else{
                tile[i][j] = 0;
            }
        }
    }
}

Upvotes: 3

Views: 65

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83366

You forgot to add typeof

This is how you would normally check for undefined.

typeof tile[i - 1][j + 1] === 'undefined'

More info on typeof


Edit, per your comment, you're doing things like this

typeof tile[i - 1][j - 1] !== 'undefined'

and getting the error of

Uncaught TypeError: Cannot read property '1' of undefined or Uncaught TypeError: Cannot read property '-1' of undefined.

Two things: that you're trying to access an index of -1 seems like it will always fail. That said, even once you fix this off-by-one error, an expression like

tile[i - 1][j - 1]

will always error out if

tile[i - 1]

is itself undefined. So you'd have to check it separately. Something like

(typeof tile[i - 1] === 'undefined' || typeof tile[i - 1][j + 1] === 'undefined')

This way if tile[i - 1] is undefined, the entire expression will "short circuit" before you get your error.

Upvotes: 4

JohnB
JohnB

Reputation: 13733

You are checking for equality with the string 'undefined' rather than with an undefined value. Try

tile[i + 1][j + 1] !== undefined

(no single quotes around undefined).

Discussion here: How to check for "undefined" in JavaScript?

Upvotes: 1

Related Questions