Javascript jquery中的简单数学

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

Simple math in jquery

javascriptjquery

提问by Darren

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.

我正在读取一个选择表单值并在 jquery 中将其乘以 50。我需要在每次乘以 50 之前将值 1 添加到选择菜单返回的数量上。我该怎么做?违规代码如下所示。

 $('#selectform').val() *50);

If I use

如果我使用

 $('#selectform').val() +1 *50);

The result is not correct.

结果不正确。

回答by Rob W

Parentheses should be used.

应该使用括号。

 ($('#selectform').val()*1 + 1) *50;

Your current expression is interpreted as:

您当前的表达式被解释为:

 var something = $('#selectform').val();
 var another   = 1 * 50;
 var result    = something + another

The *1after .val()is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:

*1之后.val()用来将字符串值转换为数字。如果省略,则表达式将被解释为:

var something = $('#selectform').val() + "1";  //String operation
var result    = something * 50;    // something is converted to a number, and
                                   //    multiplied by 50

回答by rogerlsmith

The data from $('#selectform').val()is probably being treated as a string.
Use parseInt($('#selectform').val())to convert it to an int before the multiply.

来自的数据$('#selectform').val()可能被视为字符串。
用于parseInt($('#selectform').val())在乘法之前将其转换为 int。

回答by Jayendra

Correct parentheses and use parseInt function -

更正括号并使用 parseInt 函数 -

(parseInt($('#selectform').val(),10) +1) *50;

回答by Cito

You should have a look at the operator precedence in JavaScript.

您应该看看JavaScript中的运算符优先级

回答by swatkins

You need to force the addition to happen before the multiplication with parentheses:

您需要在带括号的乘法之前强制加法:

bar myVal = ($("#selectform").val() + 1) * 50;