【发布时间】:2020-05-07 17:35:06
【问题描述】:
尝试编写这个 eval 函数,该函数接收 case,循环遍历它们,并需要检查它是否与条件数组中的条件匹配并返回 true 或 false。我不确定如何最好地格式化条件数组并在其上运行匹配。条件是嵌套的,n 级深,因此试图获得一个递归函数。
console.log(cases.forEach(c => eval(formattedCondition, c.item)))
const conditions = [
"OR",
["AND",["==","maker","airbus"],["==","name","A320"]],
["AND",[ "==", "maker","boeing"]],
["OR",["==","name","B767"]]
]
const cases = [
{
"item": {
'maker': 'airbus',
'name':"A320",
}
// should return true for this case
},
{
"item": {
'maker': 'embraer',
'name':"e175",
}
// should return false for this case
},
{
"item": {
'maker': 'boeing',
}
// should return true for this case
},
{
"item": {
'name':"B767",
}
// should return true for this case
},
{
"item": {
'maker': 'boeing',
'name':"B777",
}
// should return false for this case
},
]
【问题讨论】:
-
您能否在问题中包含您的实现/尝试制作该功能?
-
就是这样,我不确定如何格式化会影响搜索结果的条件数组
-
你能在javascript中插入想要的条件吗?
-
喜欢
or、and?是的,为什么不呢。 -
为什么
'name':"B767"的项目要返回false?它与第三个子句匹配,这就足够了。为什么最后一种情况应该返回假?中间子句接受任何波音,对名称没有任何条件,所以它应该返回 true,不是吗?
标签: javascript arrays json object