JQuery if statement with variable math operator

So I'm looking for something like this question python if statement with a variable math operator , but in jQuery / Javascript

Essentially something like

var one = "4"; var two = "6"; var op = "=="; if (one op two) { //do something } 

Is it possible?

+2
source share
5 answers

You can define many 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<b;}, ">": 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 create such a large object and don’t have complex functions, you can also 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 } 
+11
source

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

Live demo

 if (eval(one + op + two)) { //do something } 
+1
source

If you have an operation (otherwise known as a function) that you want to perform with two variables, you just 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 } 
+1
source

I recently needed something like this, and in the end I wrote a function to analyze the operator.

Sort of:

 function checkLogic(one, op, two) { switch(op) { case '==': return one == two; // etc } } 
0
source

You can use Eval to do this.

  if(eval(one+op+two)){ //do something } 
-2
source

All Articles