我正在使用 node.js,并且我正在尝试添加两个整数,但是,它们只是将它们放在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14108222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I'm using node.js, and I'm trying to add two integers, however, they just put them together
提问by Christopher Allen
I'm using node.js, and I'm trying to add two integers, however, they just put them together... I've looked up Float, trying to float the integers, but node.js doesn't recognize float.
我正在使用 node.js,我正在尝试添加两个整数,但是,它们只是将它们放在一起......我查找了 Float,试图浮动整数,但 node.js 无法识别 float .
回答by Golo Roden
Apparently at least one of both is actually a string containing a number. V8 then does string concatenation instead of adding the numbers.
显然,两者中的至少一个实际上是一个包含数字的字符串。V8 然后进行字符串连接而不是添加数字。
What you need to do is to convert the strings to real numbers. You can do that using the parseInt()or parseFloat()functions, but a faster way is to subtract 0: As subtracting from a string is not possible, V8 tries to treat the content of the string as a number.
您需要做的是将字符串转换为实数。您可以使用parseInt()orparseFloat()函数来做到这一点,但更快的方法是减去0:由于无法从字符串中减去,V8 尝试将字符串的内容视为数字。
In the end you also get a number, but AFAIK this method is faster than using the parse functions.
最后你也会得到一个数字,但 AFAIK 这个方法比使用解析函数更快。
Example:
例子:
var foo = '23';
typeof (foo - 0); // => 'number'
var a = '23',
b = '42';
console.log((a - 0) + (b - 0)); // 65
回答by Vijay13
The best way is to cast it before doing any operation for example:
最好的方法是在执行任何操作之前进行转换,例如:
var result = Number(x1) + Number(x2) - Number(x3)
回答by Muhammad Fahad
I have also same problem but solution is very simple... It's because of String data type
我也有同样的问题,但解决方案非常简单......这是因为 String 数据类型
var variable_name="1"; // String Type
console.log(parseInt(variable_name)+1);
回答by MEHA RAVI
**Add this to index.html file**
<form action="http://localhost:3000/sum" method="GET">
<input id = "one" type="number" name="first" value="">
<input id = "two" type="number" name="sec" value="">
<input type="submit" value="OK">
</form>
**Add this to javascript file**
const express = require('express');
const app = express();
app.get('/sum',function(req,res){
var a=Number(req.query.first);
var b=Number(req.query.sec);
var c;
c=a+b;
response = {
result: c
};
console.log(response);
res.end(JSON.stringify(response));
}
);
Then run the file using node.js
然后使用 node.js 运行文件
回答by Roee Gavirel
With a little delay, but for adding you can subtract the minus value, so
有一点延迟,但为了添加你可以减去负值,所以
var result = a+b; //Strings appending
becomes
变成
var result = a--b; //Integer a-(-b) --> a+b

