我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
我如何检查一个变量的类型是否为布尔类型?
我的意思是,有一些替代方案,比如:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
但这对我来说不太好。
有没有更清洁的方式来实现这个目标?
这就是typeof存在的意义。括号是可选的,因为它是一个操作符。
if (typeof variable == "boolean") {
// variable is a boolean
}
你可以使用纯Javascript来实现这一点:
var test = true;
if (typeof test === 'boolean')
console.log('test is a boolean!');
在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”。
如果你只是想检查一个原始值
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,你可以简单地使用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中的一个简单检查。
您可以创建一个函数来检查参数的typeof。
function isBoolean(value) {
return typeof value === "boolean";
}
如果你想让你的函数也可以验证布尔对象,最有效的解决方案必须是:
function isBoolean(val) {
return val === false || val === true || val instanceof Boolean;
}
使用或不使用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; }
有时我们只需要一种方法来检验。Typeof不能用于date等。所以我用
Date.prototype.getType() { return "date"; }
此外,对于数字,字符串,布尔等,我们经常需要以单一的方式检查类型…
创建像isBoolean这样的函数,它包含了一个线性typeof v === "boolean",从长远来看似乎非常不方便。我很惊讶几乎每个人都建议创建自己的函数。这似乎与扩展原生原型是一样的癌症。
您需要在参与的每个项目中重新创建它们 其他开发人员可能有不同的习惯,或者需要检查您的函数的源代码,以查看您使用的检查的实现,以了解您的检查的弱点 你会感到沮丧,当你试图写一行在控制台现场不属于你的项目
记住typeof v === "boolean"就行了。 在IDE中添加一个模板,这样就可以通过一些三个字母的快捷方式来放置它。
if(['true', 'yes', '1'].includes(single_value)) {
return true;
}
else if(['false', 'no', '0'].includes(single_value)) {
return false;
}
如果你有一个字符串
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
在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
基准:
都很相似……
const { performance } = require('perf_hooks');
const boolyah = true;
var t0 = 0;
var t1 = 0;
const loops = 1000000;
var results = { 1: 0, 2: 0, 3: 0, 4: 0 };
for (i = 0; i < loops; i++) {
t0 = performance.now();
boolyah === false || boolyah === true;
t1 = performance.now();
results['1'] += t1 - t0;
t0 = performance.now();
'boolean' === typeof boolyah;
t1 = performance.now();
results['2'] += t1 - t0;
t0 = performance.now();
!!boolyah === boolyah;
t1 = performance.now();
results['3'] += t1 - t0;
t0 = performance.now();
Boolean(boolyah) === boolyah;
t1 = performance.now();
results['4'] += t1 - t0;
}
console.log(results);
// RESULTS
// '0': 135.09559339284897,
// '1': 136.38034391403198,
// '2': 136.29421120882034,
// '3': 135.1228678226471,
// '4': 135.11531442403793
更新:以前的解决方案是更具体的,你可以选择哪个值你想考虑作为一个布尔值,你可以添加在正则表达式,如果你需要一个更通用的解决方案,不想添加一个库,然后检查下面的解决方案(从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>');
判断真假最简单的方法是: (typeof value === "boolean"), 但如果value是布尔类的实例,则返回"object"。因此,为了处理这个问题,我们必须添加另一个条件来检查是否: (value instanceof Boolean)
代码片段:
const value = false;
//const value = new Boolean(10);
//const value = new Boolean("hi");
if((typeof value === "boolean") || (value instanceof Boolean))
console.log("boolean");
else
console.log("not boolean");