所以我正在寻找类似于这个问题python if statement with variable math operator but in jQuery/Javascript
基本上像
var one = "4";
var two = "6";
var op = "==";
if (one op two) {
//do something
}
这可能吗?
所以我正在寻找类似于这个问题python if statement with variable math operator but in jQuery/Javascript
基本上像
var one = "4";
var two = "6";
var op = "==";
if (one op two) {
//do something
}
这可能吗?
你可以定义很多二进制函数:
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
}
如果您不想生成这么大的对象并且没有复杂的功能,您也可以即时生成它们(使用一点eval
魔法):
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
}
如果您想对两个变量执行一个操作(也称为函数),那么您只需定义它:
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
}
我最近需要这样的东西,最后写了一个函数来解析运算符。
就像是:
function checkLogic(one, op, two) {
switch(op) {
case '==':
return one == two;
// etc
}
}
您可以为此使用 Eval
if(eval(one+op+two)){
//do something
}