JavaScript calculations return NaN as result

浪子不回头ぞ 提交于 2019-12-13 00:27:31

问题


I am developing a html page that takes date and displays day. I am using a formula called Zeller's congruence. But in JavaScript the formula returns the Result "NaN". I googled the problem. Couldn't figure out the solution. Here is the html that takes values.

<form method="post">
<br/>
day:<input id="dd" name="dd" type="text"/><br/>
month:<input id="mm" name="mm" type="text"/><br/>
year:<input id="yy" name="yy" type="text"/><br/>
<input type="submit" value="go" onclick="day()"/><br/>
</form>

Here is the piece of JavaScript formula thats returning NaN.

function day() { 
var d=document.getElementById("dd").value;
var m=document.getElementById("mm").value;
var y=document.getElementById("yy").value;

var h=(d+(((m+1)*26)/10)+y+(y/4)+6*(y/100)+(y/400))%7;//returns NaN
var d2=((h+5)%7); code continues.. 

Please help me.

Thanks in advance.


回答1:


In some cases + signs in your formula will do string concatenation instead of sum, as in JavaScript "1" + 1 === "11". You need to convert your values from strings (as returned from form fields) to numbers with parseInt or parseFloat functions:

var d = parseInt(document.getElementById("dd").value, 10);

or to support float numbers (if required):

var d = parseFloat(document.getElementById("dd").value);

or a shortcut of Number(v):

var d = +document.getElementById("dd").value;



回答2:


  Convert your values into numbers for use parseInt();

  <script>
  function day() { 
  var D=document.getElementById("dd").value;
  var M=document.getElementById("mm").value;
  var Y=document.getElementById("yy").value;

  var d=parseInt(D);
  var m=parseInt(M);
  var y= parseInt(Y);

  var h=(d+(((m+1)*26)/10)+y+(y/4)+6*(y/100)+(y/400))%7;

  alert(h);
 }
</script>

<form method="post">
 <br/>
 day:<input id="dd" name="dd" type="text"/><br/>
 month:<input id="mm" name="mm" type="text"/><br/>
 year:<input id="yy" name="yy" type="text"/><br/>
 <input type="submit" value="go" onclick="day()"/><br/>
 </form>


来源:https://stackoverflow.com/questions/23999132/javascript-calculations-return-nan-as-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!