2

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);
    }
};
3
  • The variable of cellTracker is undefined in that function.
    – Barmar
    Commented Jun 8, 2013 at 14:24
  • @Barmar are you referring to the code in my post or the code in the link? Commented Jun 8, 2013 at 14:25
  • They're the same code. The answers explain the problem in more detail.
    – Barmar
    Commented Jun 8, 2013 at 14:28

2 Answers 2

1

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');
3
  • Even better would be to pass cellTracker as a parameter to storeMoves, instead of using an external variable.
    – Barmar
    Commented Jun 8, 2013 at 14:26
  • @Barmar: Yes, or perhaps just passing this.id.
    – user2437417
    Commented Jun 8, 2013 at 14:27
  • Oh boy, I guess I should take this as a sign that I should go to bed... Thanks for pointing that out. Commented Jun 8, 2013 at 14:29
0

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/

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.