简体   繁体   English

将变量的值推入数组将返回Void 0?

[英]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? 问题是,在我当前的代码中,xMoves和oMoves数组返回Void0。此代码有什么问题? http://jsfiddle.net/Z6StP/ http://jsfiddle.net/Z6StP/

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

void 0; is just another way of representing the undefined value. 只是表示undefined值的另一种方式。

The .push() methods are not returning void 0 . .push()方法不会返回void 0 They return the new Array length. 它们返回新的数组长度。

What you're seeing in the console is the Array with void 0 (or undefined ) inside. 您在控制台中看到的是内部为void 0 (或undefined的数组。 That's because you're pushing cellTracker into the Arrays, which is never assigned a value. 那是因为您要将cellTracker推入数组,但从未分配值。

You do have an assignment to cellTracker , but that's a local variable. 确实有对cellTracker的赋值,但这是一个局部变量。 Remove the var before it, and you'll be assigning to the outer one. 删除之前的var ,您将分配给外部的var

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

Because you define again the variable cellTracker inside the click function of the td's . 因为您再次在td's click函数中定义了变量cellTracker 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/ 小提琴: http : //jsfiddle.net/IrvinDominin/Z6StP/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM