如何使用 JavaScript 检查类型是否为布尔值

使用 JavaScript 检查类型是否为布尔值

How to check if type is Boolean using JavaScript

使用typeof运算符检查值是否为布尔类型,例如
if (typeof variable === 'boolean'). typeof运算符返回一个指示值类型的字符串。如果值为布尔值,
"boolean"则返回字符串。

索引.js
const bool = true; if (typeof bool === 'boolean') { console.log('✅ type is boolean'); } else { console.log('⛔️ type is NOT boolean'); }

我们使用
typeof
运算符来获取值的类型。

该运算符返回一个指示值类型的字符串。这里有些例子:

索引.js
console.log(typeof true); // 👉️ "boolean" console.log(typeof false); // 👉️ "boolean" console.log(typeof function () {}); // 👉️ "function" console.log(typeof null); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof {}); // 👉️ "object" console.log(typeof ''); // 👉️ "string" console.log(typeof 0); // 👉️ "number"

当与trueor的值一起使用时falsetypeof运算符返回字符串"boolean",而这正是我们在if语句中检查的内容。

索引.js
const bool = true; if (typeof bool === 'boolean') { console.log('✅ type is boolean'); }

If the condition is satisfied, the if block runs.

An alternative approach is to use the
logical OR (||)
operator.

To check if a value is of boolean type, check if the value is equal to false
or equal to true, e.g. if (variable === true || variable === false). Boolean
values can only be true and false, so if either condition is met, the value
has a type of boolean.

index.js
const bool = true; if (bool === true || bool === false) { console.log('✅ type is boolean'); } else { console.log('⛔️ type is NOT boolean'); }

We used the logical or (||) operator to chain 2 conditions. If either condition
returns a truthy value, the if block runs.

Our conditions check if the value is equal to true or equal to false.

Since booleans can only ever be true or false, if either check passes, the
value is a boolean.