我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
当前回答
在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”。
其他回答
创建像isBoolean这样的函数,它包含了一个线性typeof v === "boolean",从长远来看似乎非常不方便。我很惊讶几乎每个人都建议创建自己的函数。这似乎与扩展原生原型是一样的癌症。
您需要在参与的每个项目中重新创建它们 其他开发人员可能有不同的习惯,或者需要检查您的函数的源代码,以查看您使用的检查的实现,以了解您的检查的弱点 你会感到沮丧,当你试图写一行在控制台现场不属于你的项目
记住typeof v === "boolean"就行了。 在IDE中添加一个模板,这样就可以通过一些三个字母的快捷方式来放置它。
这就是typeof存在的意义。括号是可选的,因为它是一个操作符。
if (typeof variable == "boolean") {
// variable is a 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 test = true;
if (typeof test === 'boolean')
console.log('test is a boolean!');
更新:以前的解决方案是更具体的,你可以选择哪个值你想考虑作为一个布尔值,你可以添加在正则表达式,如果你需要一个更通用的解决方案,不想添加一个库,然后检查下面的解决方案(从lodash的布尔)
function getTag(value) {
if (value == null) {
return value === undefined ? '[object Undefined]' : '[object Null]'
}
return toString.call(value)
}
function isObjectLike(value) {
return typeof value === 'object' && value !== null
}
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && getTag(value) == '[object Boolean]')
}
之前的解决方案 const isBoolean = (val) => { const boolValuesRegex = /true|false/// Add other /true|false|1|0|on|off/ 如果(val === undefined || val === null)返回false; .toLowerCase返回boolValuesRegex.test (val.toString () ()); } 常量值=(真的,假的,“真正的”,“假”,“真正的”,“假”,“sampletext”,1,定义,null , (() => {}), {}, []]; document.body.innerHTML = values。map(x => ' ${x} - ${isBoolean(x)} ') .join('</br>');