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

如何将含value、logic字段的对象数组转换为逻辑运算并得到布尔结果

实现思路

  • 遵循JS原生逻辑运算符优先级规则:&& 优先级高于 ||,因此先计算所有与逻辑,再计算或逻辑
  • 先按or拆分逻辑组,每个组内部均为and连接的判断项
  • 逐组计算与逻辑结果,最后对所有组结果计算或逻辑得到最终值

代码实现

function calculateBooleanLogic(input: Array<{ value: boolean, logic: 'and' | 'or' }>): boolean {
    // 空输入默认返回false,可根据业务需求调整
    if (input.length === 0) return false
    // 仅一项时直接返回对应值
    if (input.length === 1) return input[0].value

    // 拆分出所有由and连接的组
    const orGroups: boolean[][] = [[]]
    input.forEach((item, index) => {
        orGroups[orGroups.length - 1].push(item.value)
        // 当前逻辑为or时,后续项归入新组
        if (item.logic === 'or' && index !== input.length - 1) {
            orGroups.push([])
        }
    })

    // 每组内执行与运算
    const groupResults = orGroups.map(group => group.every(item => item))
    // 所有组执行或运算得到最终结果
    return groupResults.some(item => item)
}

// 测试示例
const input: Array<any> = [
    {
        type: "basic",
        value: true,
        logic: "or"
    },
    {
        type: "basic",
        value: false,
        logic: "and"
    },
    {
        type: "basic",
        value: true,
        logic: "and"
    }
]

console.log(calculateBooleanLogic(input)) // 输出 true,和 `true || false && true` 运行结果一致

可选实现(忽略优先级、纯左到右运算)

如果业务要求不遵循运算符优先级,完全按数组顺序从左到右依次运算,可以用更精简的reduce实现:

function calculateLeftToRight(input: Array<{ value: boolean, logic: 'and' | 'or' }>): boolean {
    if (input.length === 0) return false
    return input.reduce((res, current, index) => {
        if (index === 0) return current.value
        return current.logic === 'and' ? res && current.value : res || current.value
    }, false)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:36:04