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

如何判断值是否为布尔原始值?为何我的代码无法通过测试

问题:判断输入是否为布尔原始值的函数写法疑问

正确实现(使用typeof)

通过typeof判断值的类型是最直接的方式,布尔原始值的typeof结果固定为'boolean',代码如下:

function booWho(bool) {
  return typeof bool === 'boolean';
}

错误写法的原因分析

1. return (bool == true||false) 和 return (bool == true|| bool == false)

  • 对于bool == true||false:JavaScript的逻辑或||会按优先级解析为(bool == true) || false。当输入是1时,==的宽松相等会触发类型转换,数字1会被转为布尔值true,导致1 == true判定为true,最终整个表达式返回true,不符合booWho(1)应返回false的要求;另外输入false时,false == true为false,再或false结果还是false,连基础测试都无法通过。
  • 对于bool == true|| bool == false:同样是宽松相等的问题,1 == true会被判定为true,导致整个表达式返回true,但1并不是布尔原始值,因此无法通过测试。

2. return (bool === true||false)

这里的核心问题是运算符优先级,表达式会被解析为(bool === true) || false。当输入是false时,false === true为false,再或false结果就是false,自然无法通过booWho(false)应返回true的测试。如果想用全等判断,正确写法应该是return bool === true || bool === false,这样才能同时匹配true和false两个布尔原始值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 18:42:08