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.

1

4 Answers 4

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))
{
    /* ... */
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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.

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.