You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript不使用eval/new Function实现动态if条件的方法咨询

实现方案:不使用eval的动态条件判断

核心逻辑是预先建立运算符映射表,把常用运算符对应到实际的判断函数,遍历所有动态条件逐一校验即可,性能和安全性都远高于动态执行代码的方案。

第一步:调整条件定义

把原来条件里attribute字段的el.前缀去掉,直接写对象的属性名即可:

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

第二步:构建运算符映射表

把你需要用到的所有运算符提前定义好对应的判断逻辑,后续要加新运算符直接往这个对象里加就行:

// 支持的运算符映射,a是对象的属性值,b是条件里的比对值
const operatorMap = {
  '>=': (a, b) => Number(a) >= b,
  '<=': (a, b) => Number(a) <= b,
  '>': (a, b) => Number(a) > b,
  '<': (a, b) => Number(a) < b,
  '==': (a, b) => a == b,
  '===': (a, b) => a === b,
  '!=': (a, b) => a != b,
  '!==': (a, b) => a !== b
}

第三步:编写动态校验的filter逻辑

不用写死判断第几个条件,直接遍历所有条件逐一校验,全部通过才返回true,不管你是3个还是4个条件都能自动适配:

var newArray = Students.filter(function(el) {
  // 所有条件都满足才返回true
  return condition.every(function(cond) {
    const attrValue = el[cond.attribute];
    // 调用对应运算符的判断方法
    return operatorMap[cond.operator](attrValue, cond.value);
  })
})

完整可运行代码

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",
}];

const operatorMap = {
  '>=': (a, b) => Number(a) >= b,
  '<=': (a, b) => Number(a) <= b,
  '>': (a, b) => Number(a) > b,
  '<': (a, b) => Number(a) < b,
  '==': (a, b) => a == b,
  '===': (a, b) => a === b,
  '!=': (a, b) => a != b,
  '!==': (a, b) => a !== b
}

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

var newArray = Students.filter(function(el) {
  return condition.every(cond => operatorMap[cond.operator](el[cond.attribute], cond.value))
})

console.log(newArray);
// 输出结果:[{name: 'Aman', Age: '14', RollNumber: '223', Marks: '69'}]

这个方案完全规避了eval和new Function,执行效率高,也不会有代码注入的安全风险,条件数量完全动态,不需要修改核心逻辑就能适配最多4个甚至更多的判断条件。

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:54:00