[英]Arithmetic operations inside the parenthesis javascript
Hi Please help me to resolve this issue 嗨,请帮我解决这个问题
var str = '10+20-10-2';
var numbers = str.replace(/ /g, '').split(/[-+*\/]/g);
var operators = str.replace(/ /g, '').split(/\d*/g);
operators.shift();
var result = +numbers[0];
for (var i = 0; i < operators.length - 1; i++) {
result = eval( result + operators[i] + numbers[i + 1] );
}
alert(result);
Above code is working fine , but when am trying to pass some other input like 上面的代码工作正常,但是在尝试传递其他输入时,例如
var str = '-(1)-(-2)';
var str = '-1-(-1)';
var str = '(-1)-2' ;
not getting any result 没有任何结果
I guess in your case, besides eval, you could also use 我想在您的情况下,除了评估外,您还可以使用
var result = parseFloat(numbers[0]);
and consequently 因此
result = eval( result + operators[i] + parseFloat(numbers[i + 1]))
This is a bit more solid because it works only if the strings in numbers REALLY contain numbers, and will return NaN
if they don't. 这更加可靠,因为仅当数字中的字符串真正包含数字时才有效,否则将返回NaN
。 Also, to be even more solid, you could go the long way and use a switch
instruction: 另外,为了更加扎实,您可以走很长一段路,并使用switch
指令:
switch(operators[i])
{
case "+":
etc.
}
Of course your solution is more elegant, but since it does not work for some reason, this might help you spot it. 当然,您的解决方案更加优雅,但是由于某种原因它无法正常工作,因此这可能会帮助您发现它。 In you, I'd also check with a couple alert()
functions the actual content of those splitted arrays. 在您中,我还将使用几个alert()
函数检查这些拆分数组的实际内容。 Sometimes regular expressions do not produce quite the output you'd expect them to. 有时,正则表达式无法产生预期的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.