我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
当前回答
如果你只是想检查一个原始值
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
其他回答
这就是typeof存在的意义。括号是可选的,因为它是一个操作符。
if (typeof variable == "boolean") {
// variable is a boolean
}
使用纯JavaScript,你可以简单地使用typeof并做一些类似typeof false或typeof true的事情,它将返回“boolean”…
但这不是唯一的方法,我在下面创建函数来展示你可以在JavaScript中检查布尔值的不同方法,也可以在一些新的框架中使用不同的方法,让我们从这个开始:
function isBoolean(val) {
return val === false || val === true;
}
或者单行ES6方式…
const isBoolean = val => 'boolean' === typeof val;
叫它像!
isBoolean(false); //return true
同样在下划线源代码中,他们像这样检查它(用_。在函数名的开头):
isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
在jQuery中,你也可以这样检查它:
jQuery.type(true); //return "boolean"
在React中,如果使用propTypes,你可以检查一个值是否为布尔值,就像这样:
MyComponent.propTypes = {
children: PropTypes.bool.isRequired
};
如果使用TypeScript,你也可以使用类型布尔:
let isDone: boolean = false;
还有另一种方法,比如将值转换为布尔值,看看它是否仍然完全相同,比如:
const isBoolean = val => !!val === val;
或者像:
const isBoolean = val => Boolean(val) === val;
叫它!
isBoolean(false); //return true
不建议使用任何框架,因为这实际上是JavaScript中的一个简单检查。
在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
你可以使用纯Javascript来实现这一点:
var test = true;
if (typeof test === 'boolean')
console.log('test is a boolean!');
if(['true', 'yes', '1'].includes(single_value)) {
return true;
}
else if(['false', 'no', '0'].includes(single_value)) {
return false;
}
如果你有一个字符串