将字符串转换为比较运算符可能与否?使用Javascript

时间:2015-06-26 21:12:05

标签: javascript

我正在创建一个过滤我的javascript对象的函数。

function filter(array,filterName,filterCondition,filterParameter){

    for(var i=0; i< array.length;i++){
        if(array[i][filterName] -<convert FilterCondition here>- filterParameter){

        }
    }

}

理想情况下我想像这样使用它:

filter(anArray,"age",">",10)

是否可以在if语句中将字符串比较运算符转换为实数运算符?

2 个答案:

答案 0 :(得分:1)

例如,您可以像这样使用哈希:

function filter(array,filterName,filterCondition,filterParameter){
    var comparisonOperatorsHash = {
        '<': 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; },
        '===': function(a, b) { return a === b; },
    };

    var comparisonOperator = comparisonOperatorsHash[filterCondition];

    if (comparisonOperator === undefined) {
        // throw error here
    }

    for(var i=0; i< array.length;i++){
        if(comparisonOperator(array[i][filterName], filterParameter)) {

        }
    }
}

答案 1 :(得分:0)

eval是邪恶的,但可以做任何事情。如果任意输入可以传递给它,就像用户输入一样,它被认为是邪恶的。但如果你控制那里的东西,它应该是安全的。更多信息here

所以你可以这样做:

&#13;
&#13;
function filter(array,filterName,filterCondition,filterParameter){
    var results = [];
    for(var i=0; i< array.length;i++){
        if(eval(array[i][filterName] + filterCondition + filterParameter)){
            results.push(array[i]['name'])
        }
    }
    document.body.innerHTML = 'These guys are older than 10: ' + results.join(', ');
}

var anArray = [
  {'name': 'Patrick', 'age': 8 },
  {'name': 'John', 'age': 12 },
  {'name': 'Debora', 'age': 26 },
  {'name': 'Jenna', 'age': 3 },
  {'name': 'Brandon', 'age': 14 },
];

filter(anArray,"age",">",10);
&#13;
&#13;
&#13;

修改

我想到了没有eval或无尽switch陈述的另一种方式。这里的技巧是创建一个临时的script标记,它将包含一个检查条件的函数。这将避免在循环的每次迭代中重新编译函数,就像eval一样。

&#13;
&#13;
var conditionScript = document.createElement('script');

function filter(array,filterName,filterCondition,filterParameter){
    var results = [];
    prepareCondition(filterCondition,filterParameter);

    for(var i=0; i< array.length;i++){
        if( evalCondition(array[i][filterName]) ){
            results.push(array[i]['name']);
        }
    }

    document.body.innerHTML = 'These guys are older than 10: ' + results.join(', ');
}

function prepareCondition(filterCondition,filterParameter){
    if(conditionScript.parentNode) document.body.removeChild(conditionScript);
    conditionScript.innerText = 'function evalCondition(value){'
                              + '    return value ' + filterCondition + filterParameter
                              + '}';
    document.body.appendChild(conditionScript);
}

var anArray=[
  {'name': 'Patrick', 'age': 8 },
  {'name': 'John', 'age': 12 },
  {'name': 'Debora', 'age': 26 },
  {'name': 'Jenna', 'age': 3 },
  {'name': 'Brandon', 'age': 14 },
];

filter(anArray,"age",">",10);
    
&#13;
&#13;
&#13;