JavaScript函数传入字符串参数为何在条件判断中匹配错误分支
问题原因
你的条件判断写法不符合JavaScript的逻辑运算规则,才会出现判断结果不符合预期的问题。
|| 逻辑或运算符会对两侧的表达式单独求值,你写的x == 'sharesLarge' || 'sharesSmall' 不会被解析为「x等于sharesLarge或者等于sharesSmall」,而是会拆分为两个独立的判断项:
- 第一个项
x == 'sharesLarge':当x为notionalLarge时,该表达式结果为false - 第二个项
'sharesSmall':非空字符串在布尔类型转换时的结果为true
因此整个if分支的判断结果为 false || true = true,程序会直接进入第一个分支输出shares,不会执行后续的else if判断。
修正方案
方案1:补全所有判断表达式
每个逻辑或的两侧都写完整的判断条件,代码如下:
console.log(x); if(x == 'sharesLarge' || x == 'sharesSmall' ) { console.log("shares"); } else if (x == 'notionalLarge' || x == 'notionalSmall' ) { console.log("notional"); } else { console.log("error"); }
方案2:用includes方法简化多值判断
如果后续需要新增可选判断值,用数组+includes方法的写法可读性更高:
console.log(x); const shareValueList = ['sharesLarge', 'sharesSmall']; const notionalValueList = ['notionalLarge', 'notionalSmall']; if(shareValueList.includes(x)) { console.log("shares"); } else if (notionalValueList.includes(x)) { console.log("notional"); } else { console.log("error"); }
额外注意:你贴出的代码末尾多了一个多余的右大括号
},建议删除避免出现语法报错。
内容的提问来源于stack exchange,提问作者JungleJim
相关产品推荐
相关产品推荐

