Javascript返回NaN

时间:2012-12-07 21:08:18

标签: javascript

我有一个函数可以对两个数字进行一些数学运算,但我似乎得到了NaN作为它的回报....我不知道为什么虽然.....这是我的功能:

function mouseConvert(mousex,mousey){

 console.log(mousex+ ' '+ mousey);

    var x = (mousex + Data.offset_x) - (settings.width/2) - settings.offset_left;
    var y = (mousey + Data.offset_y) - settings.offset_top;
    var tx = Math.round((x + y * 2) / settings.grid) - 1;
    var ty = Math.round((y * 2 - x) / settings.grid) - 1;

 console.log(tx+ ' '+ ty);

return [tx,ty];
} 

该功能的控制台日志输出显示:

enter image description here

以下是Datasettings

的值

enter image description here

为什么不返回数字而是NaN?

2 个答案:

答案 0 :(得分:3)

如果鼠标位置是"0"之类的字符串,请考虑:

(mousex + Data.offset_x)

变为

"0" + -32 //"0-32"

当您使用"0-32"进行减法时,字符串- (settings.width/2)将尝试转换为数字。 Number("0-32")NaN,之后一切都变为NaN

您应该在开头将它们转换为数字。或者更确切地说,从不将它们首先转换为字符串,因为事件对象已将它们作为数字...

答案 1 :(得分:0)

你必须将mouseX和mouseY转换为int或float parseInt或parseFloat

<html>
<head>
</head>
<body>
<script>
var Data = { ipos: NaN, jpos: NaN, level: "1", money: "1000", offset_x: -32, offset_y: -250};
var settings = { grid: 64, height: 500, offset_left: 258, offset_top: 85, width: 1165};

function mouseConvert(mousex,mousey){
 mousex = parseInt(mousex);
 mousey = parseInt(mousey); 
console.log(mousex+ ' '+ mousey);

    var x = (mousex + Data.offset_x) - (settings.width/2) - settings.offset_left;
    var y = (mousey + Data.offset_y) - settings.offset_top;
    var tx = Math.round((x + y * 2) / settings.grid) - 1;
    var ty = Math.round((y * 2 - x) / settings.grid) - 1;

 console.log(tx+ ' '+ ty);

return [tx,ty];
}
mouseConvert('0', 1);
</script> 
</body>
</html>

返回

0 1 
-25 2 

没有parseInt,它将返回 Nan