English 中文(简体)
添加加注
原标题:addition in javascript

i+j+k 但我得到了南

这里是代码:

var i = req.param( 1 , null);
      i = parseInt(i);
      var j = req.param( 2 , null);
          j = parseInt(j);

      var k = req.param( 3 , null);
         k = parseInt(k);

      var r = i+j+k;
      res.render( index , {result:r});

这是基于节点的 js

最佳回答

req.param( 2, null) 返回 null ,如果未指定参数的话。

然后调用 parseInt(null) , 给 NaN 提供 NaN

如果您在 NaN 中添加任何数字,则获得 NaN


使用 req.param( 2, 0) 代替

问题回答

如果计算中的任何值是 NaN ,您就会看到 NaN 。在您的例子中, < i , < j 和/或 NaN 。您需要查看它是哪个。请注意, parseInt 可以返回 NaN (例如, parseInt(nell) > < NaN


旁注:使用 parseInt ,例如 parseInt(i, 10) ,而不仅仅是 parseInt(i) ,几乎总是最好在使用 parseInt 时包括弧度。 这样, parseInt 不会在弧度(数字基数)处猜测。

当 JavaScript 使用 parseInt 将字符串转换为一整字时, 它会读取每个字符, 直到它看到一个非数字字符。 一个空白字符串( ) 是非数字字符, 所以会转换为 NaN

实例:

parseInt( ABC , 10); // NaN
parseInt( 123ABC , 10); // 123

所以, 您需要确保输入不是空白; 确定它是一个数字 。

P.S. 我建议将第二个参数添加到 parseInt , 它告诉它要使用什么基数。 如果它被排除, 它会试图猜测。 有时这会引起问题 :

parseInt( 12 ); // 12 (base 10)
parseInt( 012 ); // 10 (the leading  0  makes it base 8 [octal])

parseInt( 012 , 10); // 12. forced to be base 10

如果三个变量中有一个变量是 NaN, 那么它不是添加, 而是连接。 请对每个变量进行控制台. log 或提醒, 以找到单个值来查看哪个不是数字 。

EDIT... ops, 我刚刚看到你已经强迫他们使用整数。 这是很好的。 所以错误实际上发生在那个步骤... 你的一个(或更多的)数值不是一个数字, 因此不能强迫他们使用整数 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.