texasCode
texasCode

Reputation: 53

JavaScript Variable Operators

Are these possible in Javascript?

I've got something like this:

var op1 = "<";
var op2 = ">";

if (x op1 xval && y op2 yval) {
 console.log('yay');
}

Basically I need the user to input the operator, its coming from a select box.

Upvotes: 0

Views: 657

Answers (4)

scessor
scessor

Reputation: 16115

It's not nice, but possible:

var op1 = "<";
var op2 = ">";

if (eval("x"+op1+xval+" && y"+op2+yval)) {
    console.log('yay');
}

Also see my jsfiddle.
I would prefer bobbymcr answer.

Upvotes: 0

spicavigo
spicavigo

Reputation: 4224

You could do something like this.

var OpMap = {
          '>': function (a,b) return a>b;},
          '<': function (a,b) return a<b;}
}

if (OpMap[op1](x,xval) && OpMap[op2](y,yval)) {
 console.log('yay');
}

Upvotes: 0

bobbymcr
bobbymcr

Reputation: 24167

That is not possible, but this is:

var operators =
{
    '<': function(a, b) { return a < b; },
    '>': function(a, b) { return a > b; },
    /* ... etc. ... */
};

/* ... */

var op1 = '<';
var op2 = '>';
if (operators[op1](a, b) && operators[op2](c, d))
{
    /* ... */
}

Upvotes: 4

deviousdodo
deviousdodo

Reputation: 9172

Not directly, but you can create a function like this:

if (operate(op1, x, xval) && operate(op2, x, xval)) {
    console.log('yay');
}
function operate(operator, x, y) {
    switch(operator) {
        case '<':
            return x < y;
    }
}

Upvotes: 2

Related Questions