user2449973
user2449973

Reputation: 123

Pushing a variable's value into an array is returning Void 0?

I'm creating a simple tic-tac-toe game and I'm currently trying to store the user's checks into variables. The problem is, with my current code the xMoves and oMoves arrays are returning Void 0. What's wrong with this code? http://jsfiddle.net/Z6StP/

var storeMoves = function () {
    if (currentPlayer === X) {
        xMoves.push(cellTracker);
    } else if (currentPlayer === O) {
        oMoves.push(cellTracker);
    }
};

Upvotes: 2

Views: 755

Answers (2)

Irvin Dominin
Irvin Dominin

Reputation: 30993

Because you define again the variable cellTracker inside the click function of the td's. Remove the definition and use the already defined variable and it will work.

Like:

$('td').one('click', function () {
    turnCount += 1;
    setCurrentPlayer();
    $(this).text(currentPlayer);
    cellTracker = $(this).attr('id');
    storeMoves();
    console.log(turnCount, xMoves, oMoves);
});

Fiddle: http://jsfiddle.net/IrvinDominin/Z6StP/1/

Upvotes: 0

user2437417
user2437417

Reputation:

void 0; is just another way of representing the undefined value.

The .push() methods are not returning void 0. They return the new Array length.

What you're seeing in the console is the Array with void 0 (or undefined) inside. That's because you're pushing cellTracker into the Arrays, which is never assigned a value.

You do have an assignment to cellTracker, but that's a local variable. Remove the var before it, and you'll be assigning to the outer one.

/*var*/ cellTracker = $(this).attr('id');

Upvotes: 1

Related Questions