如何使用对象属性,运算符和值的字符串表示形式? [英] How to use String representation of object property, operator, and value?

查看:101
本文介绍了如何使用对象属性,运算符和值的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个字符串值"[ScheduledDate]< '11/1/2011'",并测试诸如"item"之类的对象的布尔值.但是我似乎无法找到成功完成此操作的方法.我不想使用eval函数,但是如果这是唯一的方法,那么我想我必须这样做.以下是我要使用的功能的示例.

I'm trying to use a string value of say, "[ScheduledDate] < '11/1/2011'", and test for a bool value on an object like "item". But I can't seem to be able to figure out a way to do it successfully. I'm not wanting to use the eval function, but if it's the only way, then I guess I will have to. below is an example of the function I'm trying to use.

function _filterItem2() {
        var item = { ScheduledDate: '1/1/2012' };
        var filterExpression = "[ScheduledDate] < '11/1/2011'";

        var result = item[filterExpression];  // This is where I'm not sure.

        return result;
    }

推荐答案

否,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);

这篇关于如何使用对象属性,运算符和值的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆