如何检查类型是否为布尔型

时间:2020-12-29 10:03:56

How can I check if a variable's type is of type Boolean?

如何检查变量的类型是否为布尔类型?

I mean, there are some alternatives such as:

我的意思是,有一些选择,比如:

if(jQuery.type(new Boolean()) === jQuery.type(variable))
      //Do something..

But that doesn't seem pretty to me.

但这对我来说并不好看。

Is there a cleaner way to achieve this?

有更干净的方法来实现这一点吗?

11 个解决方案

#1


260  

That's what typeof is there for. The parentheses are optional since it is an operator.

这就是typeof的作用。圆括号是可选的,因为它是一个运算符。

if(typeof(variable) === "boolean"){
  // variable is a boolean
}

A future-safe way would would be to compare with a known boolean value that is, true or false, thanks to @MarcusJuniusBrutus.

一种安全的方法是与已知的布尔值进行比较,该值是true还是false,这要感谢@MarcusJuniusBrutus。

if(typeof(variable) == typeof(true)){
  // variable is a boolean
}

#2


27  

If you just want to check for a primitive value

如果您只想检查一个原始值

typeof variable === 'boolean'

If for some strange reason you have booleans created with the constructor, those aren't really booleans but objects containing a primitive boolean value, and one way to check for both primitive booleans and objects created with new Boolean is to do :

如果出于某种奇怪的原因,您使用构造函数创建了布尔值,它们并不是真正的布尔值,而是包含原始布尔值的对象,以及一种检查原始布尔值和使用新布尔值创建的对象的方法:

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

#3


13  

You can use pure Javascript to achieve this:

您可以使用纯Javascript来实现这一点:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');

#4


11  

With pure JavaScript, just simply do this:

使用纯JavaScript,只需这样做:

function isBoolean(val) {
   return val === false || val === true;
}

Or one-line ES6 way ...

或单行ES6方式…

const isBoolean = val => 'boolean' === typeof val;

and call it!

叫它!

isBoolean(false); //return true

Also in Underscore source code they check it like this(with the _. at the start of the function name):

在下划线的源代码中,他们也像这样检查它(带有_。在函数名称的开头):

isBoolean = function(obj) {
   return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};

Also in jQuery you can check it like this:

在jQuery中也可以这样检查:

jQuery.type(true); //return "boolean"

In React, if using propTypes, you can check a value to be boolean like this:

在反应中,如果使用proptype,您可以检查一个值为布尔值:

MyComponent.propTypes = {
  children: PropTypes.bool.isRequired
};

Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:

另一种方法是,将值转换成布尔值看看它是否还是一样的,比如:

const isBoolean = val => !!val === val;

or like:

或者像:

const isBoolean = val => Boolean(val) === val;

and call it!

叫它!

isBoolean(false); //return true

It's recommended not using any framework for this as it's really a simple check in JavaScript.

建议不要为此使用任何框架,因为在JavaScript中这确实是一个简单的检查。

#5


7  

There are three "vanilla" ways to check this with or without jQuery.

有三种“普通”的方法可以检查是否使用jQuery。

  1. First, and probably most optimal, is to force boolean evaluation by coercion, then check if it's equal to the original value:

    首先,也是最优的,是强制执行布尔值,然后检查它是否等于原始值:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  2. Doing a simple typeof check:

    做一种简单的检查:

    function isBoolean( n ) {
        return typeof n === 'boolean';
    }
    
  3. Doing a completely overkill and unnecessary instantiation of a class wrapper on a primative:

    对类包装器进行完全过度和不必要的实例化:

    function isBoolean( n ) {
        return n instanceof Boolean;
    }
    

The third will only return true if you create a new Boolean class and pass that in.

如果您创建一个新的布尔类并将其传入,那么第三个将返回true。

To elaborate on primitives coercion (as shown in #1), all primitives types can be checked in this way:

要详细说明原语强制(如#1所示),可以通过以下方式检查所有原语类型:

  • Boolean:

    布尔:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  • Number:

    数量:

    function isNumber( n ) {
        return +n === n;
    }
    
  • String:

    字符串:

    function isString( n ) {
        return ''+n === n;
    }
    

#6


3  

If you want your function can validate boolean objects too, the most efficient solution must be:

如果你想让你的函数也能验证布尔对象,最有效的解决方案必须是:

function isBoolean(val) {
  return val === false || val === true || val instanceof Boolean;
}

#7


2  

The most reliable way to check type of a variable in JavaScript is the following:

在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"

The reason for this complication is that typeof true returns "boolean" while typeof new Boolean(true) returns "object".

这种复杂性的原因是true类型返回“boolean”,而新的boolean (true)类型返回“object”。

#8


2  

I would go with Lodash: isBoolean checks whether the passed-in variable is either primitive boolean or Boolean wrapper object and so accounts for all cases.

我将使用Lodash: isBoolean检查传入的变量是原始布尔还是布尔包装器对象,因此所有情况都是如此。

#9


0  

You can create a function that checks the typeof for an argument.

您可以创建一个函数来检查参数的类型。

function isBoolean(value) {
  return typeof value === "boolean";
}

#10


0  

Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by

有时我们需要一种方法来检查它。不适合约会等等,所以我很轻松

Date.prototype.getType() { return "date"; }

Also for Number, String, Boolean etc. we often need to check the type in a single way...

对于数字、字符串、布尔值等,我们通常需要以一种单一的方式检查类型……

#11


0  

Creating functions like isBoolean which contains oneliner typeof v === "boolean" seems very unhandy in long term. i am suprised that almost everyone suggest to create your own function. It seems to be same cancer as extending native prototypes.

创建像isBoolean这样包含oneliner typeof v == "boolean"的函数在长期看来非常不方便。我很惊讶,几乎每个人都建议创建自己的函数。它似乎和扩展原生原型一样。

  • you need to recreate them in every project you are involved
  • 您需要在涉及的每个项目中重新创建它们
  • other developers might have different habits,, or need to check source of your function to see which impementation of check you use, to know what are weak points of your check
  • 其他开发人员可能有不同的习惯,或者需要检查函数的源代码,查看您使用的检查的效果,了解检查的弱点
  • you will be fruustrated when you will try to write one liner in console on site which doesn't belong to your project
  • 当您尝试在控制台中编写一个不属于您的项目的班轮时,您将感到沮丧

just memoize typeof v === "boolean" and that's all. Add a template to your IDE to be able to put it by some three letter shortcut and be happy.

仅仅记住typeof v === "boolean"就够了。在你的IDE中添加一个模板,这样你就可以通过三个字母的快捷方式把它放到你的IDE中。

#1


260  

That's what typeof is there for. The parentheses are optional since it is an operator.

这就是typeof的作用。圆括号是可选的,因为它是一个运算符。

if(typeof(variable) === "boolean"){
  // variable is a boolean
}

A future-safe way would would be to compare with a known boolean value that is, true or false, thanks to @MarcusJuniusBrutus.

一种安全的方法是与已知的布尔值进行比较,该值是true还是false,这要感谢@MarcusJuniusBrutus。

if(typeof(variable) == typeof(true)){
  // variable is a boolean
}

#2


27  

If you just want to check for a primitive value

如果您只想检查一个原始值

typeof variable === 'boolean'

If for some strange reason you have booleans created with the constructor, those aren't really booleans but objects containing a primitive boolean value, and one way to check for both primitive booleans and objects created with new Boolean is to do :

如果出于某种奇怪的原因,您使用构造函数创建了布尔值,它们并不是真正的布尔值,而是包含原始布尔值的对象,以及一种检查原始布尔值和使用新布尔值创建的对象的方法:

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

#3


13  

You can use pure Javascript to achieve this:

您可以使用纯Javascript来实现这一点:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');

#4


11  

With pure JavaScript, just simply do this:

使用纯JavaScript,只需这样做:

function isBoolean(val) {
   return val === false || val === true;
}

Or one-line ES6 way ...

或单行ES6方式…

const isBoolean = val => 'boolean' === typeof val;

and call it!

叫它!

isBoolean(false); //return true

Also in Underscore source code they check it like this(with the _. at the start of the function name):

在下划线的源代码中,他们也像这样检查它(带有_。在函数名称的开头):

isBoolean = function(obj) {
   return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};

Also in jQuery you can check it like this:

在jQuery中也可以这样检查:

jQuery.type(true); //return "boolean"

In React, if using propTypes, you can check a value to be boolean like this:

在反应中,如果使用proptype,您可以检查一个值为布尔值:

MyComponent.propTypes = {
  children: PropTypes.bool.isRequired
};

Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:

另一种方法是,将值转换成布尔值看看它是否还是一样的,比如:

const isBoolean = val => !!val === val;

or like:

或者像:

const isBoolean = val => Boolean(val) === val;

and call it!

叫它!

isBoolean(false); //return true

It's recommended not using any framework for this as it's really a simple check in JavaScript.

建议不要为此使用任何框架,因为在JavaScript中这确实是一个简单的检查。

#5


7  

There are three "vanilla" ways to check this with or without jQuery.

有三种“普通”的方法可以检查是否使用jQuery。

  1. First, and probably most optimal, is to force boolean evaluation by coercion, then check if it's equal to the original value:

    首先,也是最优的,是强制执行布尔值,然后检查它是否等于原始值:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  2. Doing a simple typeof check:

    做一种简单的检查:

    function isBoolean( n ) {
        return typeof n === 'boolean';
    }
    
  3. Doing a completely overkill and unnecessary instantiation of a class wrapper on a primative:

    对类包装器进行完全过度和不必要的实例化:

    function isBoolean( n ) {
        return n instanceof Boolean;
    }
    

The third will only return true if you create a new Boolean class and pass that in.

如果您创建一个新的布尔类并将其传入,那么第三个将返回true。

To elaborate on primitives coercion (as shown in #1), all primitives types can be checked in this way:

要详细说明原语强制(如#1所示),可以通过以下方式检查所有原语类型:

  • Boolean:

    布尔:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  • Number:

    数量:

    function isNumber( n ) {
        return +n === n;
    }
    
  • String:

    字符串:

    function isString( n ) {
        return ''+n === n;
    }
    

#6


3  

If you want your function can validate boolean objects too, the most efficient solution must be:

如果你想让你的函数也能验证布尔对象,最有效的解决方案必须是:

function isBoolean(val) {
  return val === false || val === true || val instanceof Boolean;
}

#7


2  

The most reliable way to check type of a variable in JavaScript is the following:

在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"

The reason for this complication is that typeof true returns "boolean" while typeof new Boolean(true) returns "object".

这种复杂性的原因是true类型返回“boolean”,而新的boolean (true)类型返回“object”。

#8


2  

I would go with Lodash: isBoolean checks whether the passed-in variable is either primitive boolean or Boolean wrapper object and so accounts for all cases.

我将使用Lodash: isBoolean检查传入的变量是原始布尔还是布尔包装器对象,因此所有情况都是如此。

#9


0  

You can create a function that checks the typeof for an argument.

您可以创建一个函数来检查参数的类型。

function isBoolean(value) {
  return typeof value === "boolean";
}

#10


0  

Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by

有时我们需要一种方法来检查它。不适合约会等等,所以我很轻松

Date.prototype.getType() { return "date"; }

Also for Number, String, Boolean etc. we often need to check the type in a single way...

对于数字、字符串、布尔值等,我们通常需要以一种单一的方式检查类型……

#11


0  

Creating functions like isBoolean which contains oneliner typeof v === "boolean" seems very unhandy in long term. i am suprised that almost everyone suggest to create your own function. It seems to be same cancer as extending native prototypes.

创建像isBoolean这样包含oneliner typeof v == "boolean"的函数在长期看来非常不方便。我很惊讶,几乎每个人都建议创建自己的函数。它似乎和扩展原生原型一样。

  • you need to recreate them in every project you are involved
  • 您需要在涉及的每个项目中重新创建它们
  • other developers might have different habits,, or need to check source of your function to see which impementation of check you use, to know what are weak points of your check
  • 其他开发人员可能有不同的习惯,或者需要检查函数的源代码,查看您使用的检查的效果,了解检查的弱点
  • you will be fruustrated when you will try to write one liner in console on site which doesn't belong to your project
  • 当您尝试在控制台中编写一个不属于您的项目的班轮时,您将感到沮丧

just memoize typeof v === "boolean" and that's all. Add a template to your IDE to be able to put it by some three letter shortcut and be happy.

仅仅记住typeof v === "boolean"就够了。在你的IDE中添加一个模板,这样你就可以通过三个字母的快捷方式把它放到你的IDE中。