1

I have an array with the following value:

2, *, 5

How can I execute this string like so:

2 * 5

so the result returned is 10?

1
  • 1
    What about parentheses and order of operations? Commented Aug 21, 2011 at 3:40

3 Answers 3

1

The most horribly insecure way possible would be to do something like this:

eval([2,"*",5].join(''))

But I could never recommend doing that, like ever. The "right" way to do it would be to write some kind of parser.

var ops = [2,"*",5]

var val = ops.shift();
while(ops.length > 0) {
    var item = ops.shift();
    switch(item) {
        case "*": val *= ops.shift();
        case "+": val += ops.shift();
        case "-": val -= ops.shift();
        case "/": val /= ops.shift();
    }
}

This would essentially work like a very simple calculator... but I still couldn't really recommend this approach.

What are you trying to do exactly? Maybe there is a better way to model what you are trying to do other than an array?

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

9 Comments

That's really nice, as in, I like this.
@32bitkid that's what I'm trying to do, build a simple calculator. Could you please give an example of what can be done that makes using eval directly insecure?
Insecure in the sense that it executes javascript without checking it first... if the array you passed in was something like [4,"*","2;","doSomething();",8] it would return 8 (like you would expect it to), but it wouldn't do exactly what you thought it did (and it this case execute a method called doSomething). So you just have to be careful when using eval(), that you know exactly what you are evaluating. If you are trying to make a simple calculator, then I would expand more on the second approach. You can validate your user input before operating on it.
google for "Code injection" for more info about the nature of the exploit
There's way too much hype about eval security that the general public seems to think it's always evil. Eval only has security liabilities if you allow unfiltered input from a remote user. If you filter the input appropriately, then there is nothing wrong with eval and, in many cases, even unfiltered input used locally can do nothing more than people running scriptlets or greasemonkey scripts can already do on their own browser. One should be aware of where the dangers are, but not throw the baby out with the bath water. Sometimes eval is very useful and safe.
|
1

Assuming you can handle your own precedence using order and parentheses, and you are okay with using eval, then use eval:

var str = "2,*,5";
var exp = str.split(",").join("");
var n = eval(exp);
alert(n);

Also, that assumes that you have no spaces in your initial string.

4 Comments

Tell the OP to first test exp against /[0-9+\-*/()]/ for the +1 :-) Also the OP started with the array so the initial split is unncessary.
When using eval, spaces have the same importance as in any expression. In this case, they are more or less irrelevant.
@RobG - good point. Ray toal, shouldn't there be a % in there?
Sure, @karim79, a percent for modulo is good, and perhaps a decimal point, too. Depends on how much the OP wants. One could even go nuts on the sanitization and write validator code for things a regex cannot do....
0

You could just do:

var array = [2, '*', 5];
eval(array.join(''));

This is one of the few things eval is useful for, however you likely don't want to give it just anything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.