简体   繁体   中英

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. Also, to be even more solid, you could go the long way and use a switch instruction:

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. Sometimes regular expressions do not produce quite the output you'd expect them to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM