JavaScript OR(||)运算符条件判断未返回预期结果问题
问题根源
你对||(逻辑或)运算符的运行逻辑确实存在误解,这是JS初学者非常常见的语法错误。
JS中||会分别对左右两侧的独立表达式做布尔值判定,你写的判断条件characterClass === "wizard"||"sorcerer"实际会被拆成两部分执行:
- 先算左侧:
characterClass === "wizard",返回布尔值true或false - 再算右侧:单独的字符串
"sorcerer",非空字符串在JS中属于真值(truthy),永远判定为true
逻辑或运算只要任意一侧为真,整个条件就返回真,所以不管你选什么职业,这个if判断永远成立,自然永远进入第一个分支输出"Squishy boi"。
基础修正写法
逻辑或连接的每个判断条件都必须是完整的比较表达式,修正后代码如下:
let characterClass = document.getElementById("character-class").value console.log(characterClass) if (characterClass === "wizard" || characterClass === "sorcerer") { console.log("Squishy boi") } else { console.log("Not a wizard/sorcerer") }
简化多条件判断的方案
做D&D 5E角色卡需要匹配的职业规则很多(不同生命骰、豁免熟练、施法属性等),如果全堆if/else if写长串相等判断,代码会非常臃肿难维护,推荐两种更简洁的实现方式:
- 方案1:同组规则用数组收纳,用
includes()做判断
把符合同一规则的职业value统一放到数组里,直接判断当前职业是否在数组中即可,比一长串||连接的判断简洁很多:// 按规则分组配置,后续调整规则只需要改数组内容 const hitDieGroups = { d6: ["sorcerer", "wizard"], d8: ["artificer", "bard", "cleric", "druid", "monk", "rogue", "warlock"], d10: ["fighter", "paladin", "ranger"], d12: ["barbarian"] } if (hitDieGroups.d6.includes(characterClass)) { console.log("Squishy boi, hit die is d6") } else if (hitDieGroups.d8.includes(characterClass)) { console.log("Hit die is d8") } else if (hitDieGroups.d10.includes(characterClass)) { console.log("Hit die is d10") } else { console.log("Hit die is d12") } - 方案2:配置映射表(最适合角色卡场景)
直接用对象做职业到属性的映射,完全不需要写大量条件判断,查表就能拿到当前职业的所有配置,后续新增职业、调整属性只需要修改配置表:// 全职业属性配置表 const classConfig = { artificer: { hitDie: 8, saveProf: ["con", "int"], spellAbility: "int" }, barbarian: { hitDie: 12, saveProf: ["str", "con"], spellAbility: null }, bard: { hitDie: 8, saveProf: ["dex", "cha"], spellAbility: "cha" }, cleric: { hitDie: 8, saveProf: ["wis", "cha"], spellAbility: "wis" }, druid: { hitDie: 8, saveProf: ["int", "wis"], spellAbility: "wis" }, fighter: { hitDie: 10, saveProf: ["str", "con"], spellAbility: null }, monk: { hitDie: 8, saveProf: ["str", "dex"], spellAbility: null }, paladin: { hitDie: 10, saveProf: ["wis", "cha"], spellAbility: "cha" }, ranger: { hitDie: 10, saveProf: ["str", "dex"], spellAbility: "wis" }, rogue: { hitDie: 8, saveProf: ["dex", "int"], spellAbility: null }, sorcerer: { hitDie: 6, saveProf: ["con", "cha"], spellAbility: "cha" }, warlock: { hitDie: 8, saveProf: ["wis", "cha"], spellAbility: "cha" }, wizard: { hitDie: 6, saveProf: ["int", "wis"], spellAbility: "int" } } // 直接读取当前职业的所有属性,无需条件判断 const currentStats = classConfig[characterClass] console.log(`Current class hit die: d${currentStats.hitDie}`) if (currentStats.hitDie === 6) console.log("Squishy boi")
额外提醒:你当前的代码只会在页面加载时读取一次下拉框的值,用户切换职业时不会自动更新,需要给#character-class绑定change事件,触发时重新读取value、更新角色属性即可。
内容的提问来源于stack exchange,提问作者tubahorse
相关产品推荐
相关产品推荐

