判断一个javascript变量是否为布尔值,最直接也最推荐的方式是使用typeof操作符。1. typeof操作符能准确返回'boolean'来标识原始布尔值,且无副作用;2. 避免使用instanceof判断原始布尔值,因为它只适用于对象,true instanceof boolean为false;3. new boolean(false)创建的是布尔对象,typeof结果为'object',不是原始布尔值;4. !!操作符用于判断真值/假值,而非类型判断,不适用于检测是否为布尔类型;5. typeof可识别string、number、undefined、boolean、symbol、bigint和function,但null会被误判为'object',需用value === null单独判断。因此,typeof value === 'boolean'是判断原始布尔值最精准且推荐的方法。

判断一个JavaScript变量是否为布尔值,最直接也最推荐的方式就是使用
typeof
'boolean'
function isBoolean(value) {
return typeof value === 'boolean';
}
// 实际应用示例:
let statusActive = true;
let count = 10;
let userName = "Alice";
let isNull = null;
let isUndefined;
let booleanObject = new Boolean(false); // 这是一个布尔对象,不是原始布尔值
console.log(`statusActive 是布尔值吗? ${isBoolean(statusActive)}`); // true
console.log(`count 是布尔值吗? ${isBoolean(count)}`); // false
console.log(`userName 是布尔值吗? ${isBoolean(userName)}`); // false
console.log(`isNull 是布尔值吗? ${isBoolean(isNull)}`); // false
console.log(`isUndefined 是布尔值吗? ${isBoolean(isUndefined)}`); // false
console.log(`booleanObject 是布尔值吗? ${isBoolean(booleanObject)}`); // false (因为它是'object')
console.log(`直接的 false 是布尔值吗? ${isBoolean(false)}`); // truetypeof
在我看来,
typeof
true
false
typeof
'boolean'
typeof
在JavaScript中判断变量类型,尤其是布尔值,确实有一些常见的“坑”需要注意,稍不留神就可能掉进去。
一个很典型的误区是试图使用
instanceof
instanceof
true
false
instanceof
false
true instanceof Boolean
false
if (myVar instanceof Boolean)
另一个让人头疼的场景是
new Boolean()
new Boolean(true)
new Boolean(false)
typeof
'object'
new Boolean()
typeof value === 'boolean'
false
value instanceof Boolean
typeof value === 'object'
最后,也是最容易混淆的,是使用
!!
!!
!!0
false
!!""
false
!!"hello"
true
0
!!
false
0
!!
typeof
说到
typeof
'boolean'
typeof
首先是
'string'
"hello"
'world'
'number'
Infinity
NaN
NaN
number
'undefined'
undefined
typeof
'undefined'
'symbol'
typeof
'bigint'
typeof
'bigint'
然而,说到
typeof
null
'object'
null
typeof
value === null
此外,对于函数,
typeof
'function'
typeof
typeof
'object'
typeof
Array.isArray()
Object.prototype.toString.call()
以上就是js怎么判断变量是否为布尔值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号