Skip to content Skip to sidebar Skip to footer

Javascript Returns NaN

I have a function which does some maths on two numbers but i seem to get NaN as a return for it.... I don't know why though..... this is my function: function mouseConvert(mousex,

Solution 1:

Well if the mouse positions are strings like "0", consider:

(mousex + Data.offset_x)

Becomes

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

The string "0-32" will then attempted to be converted to a number when you do subtraction with - (settings.width/2). And Number("0-32") is NaN, after which everything becomes NaN.

You should convert them to a number right at the beginning. Or rather, never convert them to strings in the first place, since the event object has them as numbers already...


Solution 2:

U have to convert mouseX and mouseY to int or float parseInt or 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>

return

0 1 
-25 2 

without parseInt it will return Nan


Post a Comment for "Javascript Returns NaN"