Umair A.
Umair A.

Reputation: 6873

Javascript arithmetic operators in string array

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;

Upvotes: 0

Views: 3861

Answers (5)

pimvdb
pimvdb

Reputation: 154848

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);

Upvotes: 0

Valdas
Valdas

Reputation: 1074

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;
    }
}

Upvotes: 3

deviousdodo
deviousdodo

Reputation: 9172

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);

Upvotes: 8

Briguy37
Briguy37

Reputation: 8402

You can using eval:

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

Upvotes: 0

Lekensteyn
Lekensteyn

Reputation: 66425

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);

Upvotes: 0

Related Questions