Nan / Undefined数字属性

时间:2013-07-18 01:13:05

标签: javascript

缺点是我正在尝试创建一个Snake JS实现。为了完成游戏的“弯曲”部分,我选择使用“转折点”来跟踪蛇何时需要改变路线。为了跟踪点和方向,我使用了一个名为turnPoint的对象:

var turnPoint = {x: 0, y: 0, direction: 0};

这是我正在开始编程的课程。不确定为什么添加turnPoint.x和turnPoint.y会抛出一个未定义的异常。当我用Number()函数换行时,我得到了一个N​​an。这是一个原型问题吗?

完整源代码已在GitHub

结束
var turns = new Array();

function move(key){
    if(lastKeyPressed == null){
        lastKeyPressed = currentKey;
    }
    var delta = moveRate;
    if(currentKey == leftArrow || currentKey == upArrow){
        delta *= -1;
    }

    //only change direction if the key isn't the same, and not the opposite key up vs down, left vs right
    if(currentKey != lastKeyPressed && Math.abs(lastKeyPressed-currentKey) != 2){
        //lets create a container to hold the turning point
        var turnPoint = {x: 0, y: 0, direction: 0};

        if(lastKeyPressed == leftArrow || currentKey == leftArrow) //from left, going up or down
        {
            turnPoint = {x: Number(snakePoints[0]), y: Number(snakePoints[1]), direction: currentKey};
        }else if(lastKeyPressed == rightArrow || currentKey == rightArrow)
        {
            turnPoint = {x: Number(snakePoints[2]), y: Number(snakePoints[3]), direction:currentKey};
        }

        if(turnPoint != null){
            turns.push(turnPoint);
            console.log(turns);
        }
    }


    if(currentKey == leftArrow){
        snakePoints[0] += delta;
    }else if(currentKey == rightArrow){
        snakePoints[2] += delta;
    }else if(currentKey == upArrow){
        snakePoints[1] += delta;
    }else{
        snakePoints[3] += delta;
    }
    var newLine = new Array();

    newLine.push(snakePoints[0]);
    newLine.push(snakePoints[1]);

    for(var turn in turns){
        newLine.push(Number(turn.x));
        newLine.push(Number(turn.y));
    }

    newLine.push(snakePoints[2]);
    newLine.push(snakePoints[3]);

    console.log(newLine);

    lastKeyPressed = currentKey;
    snake.setPoints(newLine);
    drawGame();
}

1 个答案:

答案 0 :(得分:3)

for(var turn in turns){
    newLine.push(Number(turn.x));
    newLine.push(Number(turn.y));
}

在JavaScript中,for ... in循环遍历对象的属性名称,而不是属性

for (var i = 0; i < turns.length; ++i) {
  newLine.push(Number(turns[i].x));
  newLine.push(Number(turns[i].y));
}

你真的不应该在数组上使用for ... in,除非你真的知道你需要这样做。