How to execute an arithmetic operation inside a string in Javascript? - Stack Overflow

I have this little example:var myoperation = "2+2";var myoperation2="2*53";var m

I have this little example:

var myoperation = "2+2";
var myoperation2="2*5/3";
var myoperation3="3+(4/2)"

is there anyway to execute this and get a result?

Thanks a lot in advance!

I have this little example:

var myoperation = "2+2";
var myoperation2="2*5/3";
var myoperation3="3+(4/2)"

is there anyway to execute this and get a result?

Thanks a lot in advance!

Share Improve this question asked May 19, 2013 at 13:21 Gabriel R.Gabriel R. 413 silver badges7 bronze badges 5
  • 1 What all operations can the string have? – Dogbert Commented May 19, 2013 at 13:22
  • 1 eval, which is also evil. – Antony Commented May 19, 2013 at 13:24
  • 1 There's eval, or there's creating a script to parse the file manually. Which you use depends on how much effort you're willing to spend, and whether this is user input or not. – Qantas 94 Heavy Commented May 19, 2013 at 13:25
  • 1 eval() seems to work just fine. However, unless it is used very judiciously and cautiously, it would really break your code. – Achrome Commented May 19, 2013 at 13:26
  • eval will parse and execute whatever is in the string, but it's slow and can be dangerous. The only other option would be to parse the string and do the calculations yourself. – adeneo Commented May 19, 2013 at 13:26
Add a ment  | 

6 Answers 6

Reset to default 3

You can use the eval() function. For eg: eval("2+2")

Use eval MDN: https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/eval

Some people say it is evil, but it was designed for this exact purpose;

console.log(eval(myoperation)); // 4
console.log(eval(myoperation2)); // 3.33
console.log(eval(myoperation3)); // 5

You could do this besides eval:

function run(myoperation) {
    return new Function('return ' + myoperation + ';').call();
}

run('2+2'); // return 4

You can use eval for this.

Don't pass any data from a remote server to eval before validating it. Damage can be done with eval.

Pass the string to eval() function.

you can use Function

var result = new Function("return " + "2+2")();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744847850a4596951.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信