jQuery if语句带有变量数学运算符 [英] jQuery if statement with variable mathematical operator
本文介绍了jQuery if语句带有变量数学运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我正在寻找类似于这个问题的内容 python if if statement with variable数学运算符但是在jQuery / Javascript中
So I am looking for something similar to this question python if statement with variable mathematical operator but in jQuery/Javascript
基本上类似于
var one = "4";
var two = "6";
var op = "==";
if (one op two) {
//do something
}
这可能吗?
推荐答案
你可以定义很多二元函数:
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<b;},
">": function(a,b){return a>b;},
…
};
var one = "4",
two = "6",
op = "==";
if (op in operators && operators[op](+one, +two)) {
//do something
}
如果您不想生成如此大的对象且没有复杂的功能,您也可以即时生成它们(使用一点 eval
magic):
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
}
这篇关于jQuery if语句带有变量数学运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文