0

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.

texasCode
  • 53
  • 2
  • Possible duplicate of [Are Variable Operators Possible?](https://stackoverflow.com/questions/5834318/are-variable-operators-possible) – Gary May 22 '18 at 21:00

4 Answers4

4

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))
{
    /* ... */
}
bobbymcr
  • 23,769
  • 3
  • 56
  • 67
2

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;
    }
}
deviousdodo
  • 9,177
  • 2
  • 29
  • 34
0

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.

scessor
  • 15,995
  • 4
  • 43
  • 54
0

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');
}
spicavigo
  • 4,116
  • 22
  • 28