Javascript 如何将两个字符串相加,就好像它们是数字一样?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8976627/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:16:52  来源:igfitidea点击:

How to add two strings as if they were numbers?

javascript

提问by Andrew

I have two strings which contain only numbers:

我有两个只包含数字的字符串:

var num1 = '20',
    num2 = '30.5';

I would have expected that I could add them together, but they are being concatenated instead:

我原以为我可以将它们加在一起,但它们被连接起来了:

num1 + num2; // = '2030.5'

How can I force these strings to be treated as numbers?

如何强制将这些字符串视为数字?

回答by ChaosPandion

I would use the unary plus operator to convert them to numbers first.

我会先使用一元加号运算符将它们转换为数字。

+num1 + +num2;

回答by mrtsherman

MDN docs for parseInt
MDN docs for parseFloat

parseInt 的
MDN 文档 parseFloat 的 MDN 文档

In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0is treated as octal. This would obviously cause problems!

在 parseInt 中基数被指定为 10,所以我们在基数 10 中。在非严格的 javascript 中,前面的数字0被视为八进制。这显然会引起问题!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.

另请参阅 ChaosPandion 的答案,了解使用一元运算符的有用快捷方式。我已经设置了一个小提琴来显示不同的行为。

http://jsfiddle.net/EtX6G/

http://jsfiddle.net/EtX6G/

var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];

Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);

function Append(text) {
    body.appendChild(document.createTextNode(text));
    body.appendChild(document.createElement('br'));
}

回答by Luca Borrione

I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:

我建议使用一元加运算符,强制将最终字符串视为数字,在括号内使代码更具可读性,如下所示:

(+varname)

So, in your case it's:

所以,在你的情况下,它是:

var num1 = '20',
    num2 = '30.5';

var sum = (+num1) + (+num2);

// Just to test it
console.log( sum ); // 50.5

回答by undefined

var result = Number(num1) + Number(num2);

回答by Kristian

convert the strings to floatswith parseFloat(string)or to integerswith parseInt(string)

将字符串转换为floatswithparseFloat(string)或 to integerswithparseInt(string)

回答by kugyousha

If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:

如果您需要将两个非常大的字符串相加,您需要在每个字符串位置评估相加:

function addStrings(str1, str2){
  str1a = str1.split('').reverse();
  str2a = str2.split('').reverse();
  let output = '';
  let longer = Math.max(str1.length, str2.length);
  let carry = false;
  for (let i = 0; i < longer; i++) {
    let result
    if (str1a[i] && str2a[i]) {
      result = parseInt(str1a[i]) + parseInt(str2a[i]);

    } else if (str1a[i] && !str2a[i]) {
      result = parseInt(str1a[i]);

    } else if (!str1a[i] && str2a[i]) {
      result = parseInt(str2a[i]);
    }

    if (carry) {
        result += 1;
        carry = false;
    }
    if(result >= 10) {
      carry = true;
      output += result.toString()[1];
    }else {
      output += result.toString();
    }
  }
  output = output.split('').reverse().join('');

  if(carry) {
    output = '1' + output;
  }
  return output;
}

回答by Gurwinder Singh

You can use this to add numbers:

您可以使用它来添加数字:

var x = +num1 + +num2;

回答by Nicholas Carey

try

尝试

var x = parseFloat(num1) + parseFloat(num2) ;

or, depending on your needs:

或者,根据您的需要:

var x = parseInt(num1) + parseInt(num2) ;

http://www.javascripter.net/faq/convert2.htm

http://www.javascripter.net/faq/convert2.htm

You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also

您可能想要阅读Douglas Crockford所著的Javascript: The Good Parts一书。Javascript 有相当多的陷阱!这本书对澄清它们大有帮助。也可以看看

and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.

和 Crockford 先生的优秀论文Javascript:世界上最容易被误解的编程语言

回答by adam0101

I've always just subtracted zero.

我一直只是减去零。

num1-0 + num2-0;

Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.

假设一元运算符方法少了一个字符,但并不是每个人都知道一元运算符是什么,或者当他们不知道它叫什么时如何通过谷歌来找出它。

回答by Soham Das

function sum(){
    var x,y,z;
    x = Number(document.getElementById("input1").value);
    y = Number(document.getElementById("input2").value);
    z = x + y;
    document.getElementById("result").innerHTML = z ;
}