【问题标题】:Dynamic if conditions in JavaScriptJavaScript 中的动态 if 条件
【发布时间】:2021-11-18 08:20:32
【问题描述】:

无论如何,如果不使用影响其性能的 eval() 或 new function() 来动态传递 if 语句的条件及其运算符。

<script>

var Students =  [{
            "name": "Raj",
             "Age":"15",
            "RollNumber": "123",
            "Marks": "99",
              
        }, {
            "name": "Aman",
             "Age":"14",
            "RollNumber": "223",
            "Marks": "69",
           },
           {
            "name": "Vivek",
             "Age":"13",
            "RollNumber": "253",
            "Marks": "89",
           }
        ];



*Number of condition are dynamic. can even contain 3 or 4 condition at a time*

var condition = [{"attribute":"el.Age","operator":">=","value":14},
                 {"attribute":"el.Marks","operator":"<=","value":70}];

var newArray =Students.filter(function (el)
{
  if( condition[0].attribute condition[0].operator condition[0].value && condition[1].attribute condition[1].operator condition[1].value ){
  
return true;
  
});

console.log(newArray);
</script>

【问题讨论】:

    标签: javascript arrays object if-statement dynamic


    【解决方案1】:

    是的,您将操作数和运算符传递到一个函数中,该函数根据运算符分派给执行操作的对象。

    作为代码草图:

    const operators = new Map([
        ["<", lt],
        [">", gt],
        ["<=", lte],
        [">=", gte],
        // ...
    ]);
    function evaluate(operator, leftOperand, rightOperand) {
        const evaluator = operators.get(operator);
        if (!evaluator) {
            throw new Error(`Unknown operator ${operator}`);
        }
        return evaluator(leftOperand, rightOperand);
    }
    

    ...其中ltgt 等是执行操作的函数。我在上面使用了operatorleftOperandrightOperand,但如果您愿意,可以使用attributevalue。你需要like this 来获取“属性”的值(JavaScript 术语是“属性”)。

    (或者您可以在 evaluate 函数本身中执行大 switch 中的操作。)

    然后你在filter中使用那个函数:

    let newArray = Students.filter(student => conditions.every(({operator, attribute, value}) => {
        const leftOperand = getProperty(student, attribute);
        return evaluate(operator, leftOperand, value);
    }));
    

    我在那里使用了every,因为您使用的是&amp;&amp; 条件。 (注意我将condition 数组重命名为conditions,因为数组包含多个值。)

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2014-07-05
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多