+ 5

question about Javascript?

I created a function and I want to behavior with that function's element like javascript code. you will understand my meaning with the following example: function a(elem){ } a("2+2") answer=4 a("5^2") answer=25 a("4+2+9") answer=15 a("6*5+4") answer=34 Can you help me?

22nd Nov 2017, 6:05 PM
sepehr karimi (sk12.ir)
sepehr karimi (sk12.ir) - avatar
2 Answers
+ 4
You're passing in a string expression to be evaluated, so you could just use the eval() function by itself or return eval(elem) which will return the evaluation from your function. function a(elem) { return eval(elem); } x = a("2 + 2"); alert(x); or just: x = eval("2 + 2"); alert(x);
22nd Nov 2017, 7:02 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
thanks a lot
22nd Nov 2017, 8:10 PM
sepehr karimi (sk12.ir)
sepehr karimi (sk12.ir) - avatar