JavaScript相等性比较函数逻辑异常,请求排查修正
问题分析
你的函数在传入(1, true)时返回"The type is different.",原因是JavaScript的宽松相等运算符==会触发隐式类型转换:布尔值true会被转换为数字1,因此1 == true的结果为true,同时typeof 1是number、typeof true是boolean,类型不同,刚好匹配第二个分支的判断逻辑。
但你期望这个场景返回"The value and type are different.",说明你对“值相等”的定义是字面意义上的内容一致,而非隐式转换后的相等。
修正方案
我们调整判断逻辑,先区分类型是否相同,再针对类型不同的场景,自定义你认可的“值相等”规则(比如仅数字与对应字符串的匹配):
function checkEquality(a, b) { // 严格相等:类型和值完全匹配 if (a === b) { return "The type and values are equal."; } // 类型相同但值不同 if (typeof a === typeof b) { return "The value and type are different."; } // 自定义“值相等但类型不同”的规则:仅数字与对应字符串匹配的情况 const isNumberStringMatch = (typeof a === 'number' && typeof b === 'string' && a.toString() === b) || (typeof b === 'number' && typeof a === 'string' && b.toString() === a); if (isNumberStringMatch) { return "The type is different."; } // 其他类型不同且值不匹配的情况 return "The value and type are different."; } console.log(checkEquality(1, true)); // 输出: "The value and type are different." console.log(checkEquality(0, "0")); // 输出: "The type is different." console.log(checkEquality(1, 1)); // 输出: "The type and values are equal."
如果需要更宽泛的“值相等”定义(比如包含false和0的匹配),可以修改isNumberStringMatch的判断条件,加入对应的规则即可。
内容的提问来源于stack exchange,提问作者Kat Shepil
相关产品推荐
相关产品推荐

