R
R
Rapen2016-09-05 21:23:23
OOP
Rapen, 2016-09-05 21:23:23

Why does the method return NaN?

In general, there is a method that accepts a string-numbers with an arithmetic operation, which in fact should return the result, those are converted and how to convert normally, and return the result of addition, for example?

function Calculator() { 

  this.calculate = function (str){
    
    
    return +str;
  }
}

var calc = new Calculator();

console.log(calc.calculate("2 + 4")); // 6

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2016-09-05
@SagePtr

If you trust the expression, you can evaluate it with the eval function (dangerous and not recommended). If not, there are third-party libraries for parsing and evaluating mathematical expressions, such as mathjs.org

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question