Javascript 如何将存储在字符串中的数值相加?

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

How to add together numerical values that are stored in strings?

javascript

提问by sriramjitendra

I'm trying to add 1to my JavaScript variable, but the following code doesn't give expected results:

我正在尝试添加1到我的 JavaScript 变量中,但以下代码没有给出预期的结果:

var val1 = document.getElementById('<%= rng1.ClientID %>');
var val2 = val1.value + "1";
alert(val2.value);

How can I do this?

我怎样才能做到这一点?

回答by Franck Freiburger

you can use the function parseInt() to transform the string stored in val1.value into a number:

您可以使用函数 parseInt() 将存储在 val1.value 中的字符串转换为数字:

var val2 = parseInt(val1.value) + 1;

Note that Number(val1.value)will also convert your value into a number.

请注意,这Number(val1.value)也会将您的值转换为数字。

-edit-
As yc suggest, is highly recommended to use parseInt(val1.value, 10) + 1;because if your string starts with a "0"the string is interpreted as octal. eg. parseInt("0123") == 83and not 123

-edit-
正如 yc 建议的那样,强烈建议使用,parseInt(val1.value, 10) + 1;因为如果您的字符串以 a 开头,则"0"该字符串将被解释为八进制。例如。parseInt("0123") == 83而不是 123

回答by Ivo Wetzel

The simplest and also preferred way would be to use +to cast to a number.

最简单也是首选的方法是使用+强制转换为数字。

Examples:

例子:

+'234'; // 234
+'042'; // 42! It does not convert to octal

In your case:

在你的情况下:

var val1 = +(document.getElementById('<%= rng1.ClientID %>').value); // () added just for the looks
var val2 = val1.value + 1; // if val1 is 5, val2 will be 6 hooray!
alert(val2); // just val2, since it's a plain number not an html input element

回答by Saleh

parseInt($('.scpContainer').height()+200)

回答by Wella

In an external JavaScript file you can't use the <%=ControlID.ClientID %>to get the client id.

在外部 JavaScript 文件中,您不能使用<%=ControlID.ClientID %>来获取客户端 ID。

If there you using an external JavaScript file you need to pass client id value to that function.

如果您在那里使用外部 JavaScript 文件,则需要将客户端 ID 值传递给该函数。

回答by Patrik Fiala

you must add number, so try it without quotes :-)

您必须添加数字,因此请尝试不带引号:-)