javascript typeof / NaN混乱

时间:2014-06-23 19:29:17

标签: javascript variables return nan typeof

所以我正在使用canvas API制作一个小游戏,而且我对Javascript还不熟悉。但是当我正在努力让charecter能够完全拍摄360度时,我在下面的代码中遇到了一个错误(这个函数应该返回鼠标位置和玩家位置之间的角度)

calculateAngle : function(x,y){

    var opp = 0; //opposite
    var adj = 0; //adjecent
    var rad = 0; //radian
    var ang = 0; //angle

    //side lengths
    var x1 = gfx.player_center_x //the player x position
    var x2 = mouse_x; //the mouse x position
    var y1 = gfx.player_center_y; //the player y position
    var y2 = mouse_y; //the mouse y position

    //find 2 lengths of the triangle
    opp = (y2 - y1);
    adj = (x2 - x1);

    //find the missing angle between the adjecent and hypotenuse
    rad = Math.atan2(adj, opp);
    ang = rad * 180 / Math.PI;

    //-------------------------//
    console.log(ang); //prints: NaN
    console.log(typeof ang); //prints: number 
    //------------------------//

    return ang;
}

执行时返回NaN但是ang是一个数字! 为什么javascript认为变量不是数字?它声明为0哪种类型返回号码,请帮忙!

更新:发生粗心错误,x1和y1等更改位置,我忘了实施它,谢谢你的回答

1 个答案:

答案 0 :(得分:0)

NaN是一个特殊值。在内部它是一个数字,但它是一个特定的值,赋予“这个值在数学上未定义”的特殊含义。任何导致未定义数字的操作(例如0/0)都会导致NaN,但它仍然是一个数字!只是没有定义的数字。

Math.atan2的实现方式使其无法返回NaN(因为它处理y/xInfinity的“边缘情况” - 另一个“数字”这不是一个定义的数字)所以几乎可以肯定你的NaN来自opp和/或adj的计算。您应该记录这些值,看看是什么。