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

2022-01-29 00:00:00 javascript

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

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?

推荐答案

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

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

+num1 + +num2;

相关文章