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
6 Answers
Reset to default 3You 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条)