我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
当前回答
使用或不使用jQuery,有三种“普通”方法来检查这一点。
首先是强制布尔值,然后检查它是否等于原始值: 函数isBoolean(n) { 返回! !N === N; } 做一个简单的检查: 函数isBoolean(n) { 返回typeof n === 'boolean'; } 在原语上对类包装器进行完全过度且不必要的实例化: 函数isBoolean(n) { 返回n instanceof Boolean; }
第三个函数只有在创建一个新的布尔类并将其传入时才会返回true。
为了详细说明基元强制(如#1所示),所有基元类型都可以这样检查:
布尔: 函数isBoolean(n) { 返回! !N === N; } 数量: 函数isNumber(n) 返回+n === n; } 字符串: 函数isString(n) { 返回" +n === n; }
其他回答
The most readable: val === false || val === true. Also readable: typeof variable == typeof true. The shortest, but not readable at all: !!val === val. Explanation: [!!] The double exclamation mark converts the value into a Boolean. [===] The triple equals test for strict equality: both the type (Boolean) and the value have to be the same. If the original value is not a Boolean one, it won't pass the triple equals test. If it is a Boolean variable, it will pass the triple equals test (with both type & value). Tests: !!5 === 5 // false !!'test' === 'test' // false let val = new Date(); !!val === val // false !!true === true // true !!false === false // true
您可以创建一个函数来检查参数的typeof。
function isBoolean(value) {
return typeof value === "boolean";
}
如果你只是想检查一个原始值
typeof variable === 'boolean'
如果出于某种奇怪的原因,你使用构造函数创建了布尔值,这些布尔值并不是真正的布尔值,而是包含一个基本布尔值的对象,检查基本布尔值和使用new boolean值创建的对象的一种方法是:
function checkBool(bool) {
return typeof bool === 'boolean' ||
(typeof bool === 'object' &&
bool !== null &&
typeof bool.valueOf() === 'boolean');
}
function checkBool(bool) { return typeof bool === 'boolean' || (typeof bool === 'object' && bool !== null && typeof bool.valueOf() === 'boolean'); } console.log( checkBool( 'string' )); // false, string console.log( checkBool( {test: 'this'} )); // false, object console.log( checkBool( null )); // false, null console.log( checkBool( undefined )); // false, undefined console.log( checkBool( new Boolean(true) )); // true console.log( checkBool( new Boolean() )); // true console.log( checkBool( true )); // true console.log( checkBool( false )); // true
在JavaScript中检查变量类型最可靠的方法是:
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"
造成这种复杂性的原因是typeof true返回“boolean”,而typeof new boolean (true)返回“object”。
在nodejs中,通过使用node-boolify,我们可以使用isBoolean();
var isBoolean = require('node-boolify').isBoolean;
isBoolean(true); //true
isBoolean('true'); //true
isBoolean('TRUE'); //false
isBoolean(1); //true
isBoolean(2); //false
isBoolean(false); //true
isBoolean('false'); //true
isBoolean('FALSE'); //false
isBoolean(0); //true
isBoolean(null); //false
isBoolean(undefined); //false
isBoolean(); //false
isBoolean(''); //false