0

So I am trying to get a button to display the result of a math expression. The problem is that the math expression is stored in a string. This is the code:

function bEqu(){
    var test = "2 + 2";
    document.getElementById("numButtons").innerHTML += "<br>" + test;
    //I am trying to get it to return 4.
}
0

3 Answers 3

2

Just eval it.

document.getElementById("numButtons").innerHTML += "<br>" + eval(test);

However, keep it in mind that use eval only for simple math calculations and not for anything else because eval is evil.

Sign up to request clarification or add additional context in comments.

5 Comments

I'll guess that the OP is building a calculator with buttons, so probably building the expression rather than executing arbitrary script.
@RobG Well, let him post another question on that. As it stands now, my answer answers what OP wants ;)
Yes, just meant that it's probably fine to use eval for this. :-)
@RobG, sorry for misinterpreting things. I ain't a native English speaker ;)
That's fine, I didn't say it very well. :-)
0
function bEqu(){
    var test = "2 + 2";
    document.getElementById("numButtons").innerHTML += "<br>" + eval(test);
    //You have returned 4.
    //using eval(test);
}

2 Comments

Give some explanations too with your code, its in low quality post.
ya. I have commented the explanation right? eval() is used to evaluate the expression.
-1

eval(test) gives you the proper result 4.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.