0

The input values are stored in an array, the below loop is to calculate the final result, by looping through the array and appending the operators and numbers to a variable which is then evaluated.

privateCalculate = function () {
    var total;

    for(i = 0; i < init.sequence.length; i++) {
        if(init.sequence[i] === "+" || init.sequence[i] === "-" ||
           init.sequence[i] === "*" || init.sequence[i] === "/" ||
           init.sequence[i] === "(" || init.sequence[i] === ")") 
        {
            total += init.sequence[i];
        } else {
            init.sequence[i] = parseFloat(init.sequence[i]);

            total += init.sequence[i];
        }

    }

    console.log(eval(total));
    //console.log((parseFloat(1)+parseFloat(2))/parseFloat(2));
},

The function produces "NaN"

5
  • please print the content of init.sequence Commented Nov 23, 2015 at 23:41
  • ["5", "+", "5"], the if logic is intended to convert "5" to 5 Commented Nov 23, 2015 at 23:45
  • Drop the parseFloat, your strings will be converted to ints with eval anyway Commented Nov 23, 2015 at 23:53
  • the numbers are being converted back to strings anyway, so this makes no sense. just join the values total=init.sequence.join("") Commented Nov 23, 2015 at 23:56
  • What??? Sorry but if you have var arr = ["10","+","5","-","2","*","3"] >>> this is all you need: eval(arr.join("")) Commented Nov 23, 2015 at 23:57

1 Answer 1

1

You said your input is: ["5","+","5"] You don't need to parse it, because evaltakes as parameter a String

Just do this:

var inputArray = ["5","+","5"];
eval(inputArray.join('')) // -> 10
Sign up to request clarification or add additional context in comments.

3 Comments

Yes. Exactly what I said in comments. Though be careful not to allow global access to the eval or trough function arguments/ callbacks etc. In that case it could be exploited to attacks.
@RokoC.Buljan two dumb guys, one though :)
Yes, eval is a "feature" unless you knew it :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.