0

I have following array.

var signs = ['+', '-', '*', '/'];

And following variables to add with each sign above in the array.

var right_digit = 1;
var left_digit = 5;

Can I do something like below in JS?

var answer = left_digit sign[0] right_digit;
2
  • Why would you want to do that? Every implementation of such is slower than 1 + 5. Commented Oct 31, 2011 at 21:23
  • It's a game where I need to randomly select the sign. Commented Oct 31, 2011 at 21:24

5 Answers 5

8

If you want to avoid eval you can do something like:

var signs = {
    '+': function(op1, op2) { return op1 + op2; },
    ...
};

var answer = signs['+'](left_digit, right_digit);
Sign up to request clarification or add additional context in comments.

Comments

3

I'm pretty sure you can't do this, but you can make a function which does that.

function action(a, b, c) {
    switch (c) {
        case "+":
            return a+b;
        case "-":
            return a-b;
        case "*":
            return a*b;
        default:
            return a/b;
    }
}

Comments

0

You can use eval if you want dynamically evaluate operators in that way:

var answer = eval(right_digit + sign[0] + left_digit);

Note that the use of `eval is not recommended because of potentional security issues (if the data is untrusted) and slow because the code has to be analysed each time it's executed.

A better way would be using a switch like this:

function calculate(a, operator, b) {
    switch (operator) {
      case "+":
        return a + b;
      case "-":
        return a - b;
      case "*":
        return a * b;
      case "/":
        return a / b;
    }
}
var answer = calculate(right_digit, sign[0], left_digit);

2 Comments

@AlienWebguy It's one of the possibilities, I do not recommend it.
To be fair when I made my comment, eval() was the entirety of your answer ;)
0

You can using eval:

var answer = eval(left_digit + sign[0] + right_digit);

Comments

0

A safe eval solution (will filter digits and sign, and throw an error if it isn't in that format):

function calculate(expr) {
    var matches = /^(\d+)([+\-*/])(\d+)$/.exec(expr);

    if(!matches) {
        throw "Not valid";
    }

    return eval(matches[1] + matches[2] + matches[3]);
}

calculate('2*4'); // 8

So you can do:

calculate(left + sign + right);

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.