且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用对象属性,运算符和值的字符串表示形式?

更新时间:2023-09-05 22:33:10

否,item[filterExpression]只会返回名称类似于您的字符串的属性.

No, item[filterExpression] would just return the property named like your string.

相反,您应该将过滤器表达式存储为对象:

Instead, you should store your filter expression as an object:

var filter = {
    propname: "ScheduledDate",
    operator: "<",
    value: "1/1/2012"
};

然后获取比较值:

var val1 = item[filter.propname],
    val2 = filter.value;

现在是棘手的部分.没错,您不应使用eval.但是不可能从运算符名称中获取相应的功能,因此您需要自己编写代码.您可以使用switch语句或类似的映射:

and now comes the tricky part. You are right, you should not use eval. But there is no possibility to get the corresponding functions from operator names, so you will need to code them yourself. You might use a switch statement or a map like this:

var operators = {
    "<": function(a,b){return a<b;},
    ">": function(a,b){return a>b;},
    ...
};
var bool = operators[filter.operator](val1, val2);