Organizational Research By

Surprising Reserch Topic

jquery if statement with variable mathematical operator


jquery if statement with variable mathematical operator  using -'javascript,jquery'


  Possible Duplicate:
  Is there a way to make a comparison operator a variable?  




So I am looking for something similar to this question python if statement with variable mathematical operator but in jQuery/Javascript

Essentially something like

var one = "4";

var two = "6";

var op = "==";

if (one op two) {
//do something
}


is this possible?
    

asked Sep 15, 2015 by StepanieStur
0 votes
95 views



Related Hot Questions

4 Answers

0 votes

You could define a lot of binary functions:

var operators = {
    "==": function(a,b){return a==b;},
    "<=": function(a,b){return a<=b;},
    ">=": function(a,b){return a>=b;},
    "<": function(a,b){return a": function(a,b){return a>b;},
    …
};

var one = "4",
    two = "6",
    op = "==";
if (op in operators && operators[op](+one, +two)) {
    //do something
}

If you don't want to generate such a large object and have no complex functions, you also might be able to generate them on-the-fly (using a bit of eval magic):

var validOps = /^([!=<>]=|<|>)$/,
    operators = {};
function check(op, x, y) {
    if (arguments.length > 1)
        return check(op)(x, y);
    if (op in operators)
        return operators[op];
    if (validOps.test(op))
        return operators[op] = new Function("a","b","return a "+op+" b;");
    return function(a, b){return false;};
}

if (check("==", 4, 6)) {
    // do something
}
answered Sep 15, 2015 by GlaRYP
0 votes

You can use eval() but it should be a string that could be evaluated to javascript to get the desired results.

Live Demo

if (eval(one + op + two)) {
    //do something
}
answered Sep 15, 2015 by JesBourget
0 votes

If you have an operation (otherwise known as a function) that you'd like to perform on two variables, then you simply need to define it:

var operations,
    a,
    b,
    op;
operations = {
    '==': function (a, b) {
        return a == b;
    },
    '&&': function (a, b) {
        return a && b;
    },
    '||': function (a, b) {
        return a || b;
    }
};
a = 4;
b = 6;
op = operations['=='];
if (op(a, b)) {
    //do stuff
}
answered Sep 15, 2015 by EveHannell
0 votes

I needed something like this recently and ended up writing a function to parse the operator.

Something like:

function checkLogic(one, op, two) {
    switch(op) {
        case '==':
            return one == two;
        // etc
    }
}
answered Sep 15, 2015 by EpifaniaRand

...