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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28814585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:27:58  来源:igfitidea点击:

How to check if type is Boolean

javascriptjquerytypes

提问by Matias Cicero

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?

有没有更清洁的方法来实现这一目标?

回答by Amit Joki

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

这就是为什么typeof。括号是可选的,因为它是一个运算符

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

回答by adeneo

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 Booleanis to do :

如果由于某种奇怪的原因你用构造函数创建了布尔值,那些不是真正的布尔值,而是包含原始布尔值的对象,检查原始布尔值和使用创建的对象的一种方法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

回答by Alireza

With pure JavaScript, you can just simply use typeofand do something like typeof falseor typeof trueand it will return "boolean"...

使用纯 JavaScript,您可以简单地使用typeof并执行类似typeof falseor 的操作typeof true,它会返回"boolean"...

But that's not the only way to do that, I'm creating functions below to show different ways you can check for Booleanin JavaScript, also different ways you can do it in some new frameworks, let's start with this one:

但这不是唯一的方法,我在下面创建函数以展示您可以在 JavaScript 中检查布尔值的不同方式,以及您可以在一些新框架中执行此操作的不同方式,让我们从这个开始:

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

Or one-line ES6way ...

或者单行ES6方式...

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

and call it like!

并称之为!

isBoolean(false); //return true

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

同样在Underscore源代码中,他们像这样检查它(在函数名称的开头使用 _.):

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

Also in jQueryyou 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:

React 中,如果使用 propTypes,您可以像这样检查一个值为布尔值的值:

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

If using TypeScript, you can use type booleanalso:

如果使用TypeScript,您也可以使用类型boolean

let isDone: boolean = false;

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 not recommended using any framework for this as it's really a simple check in JavaScript.

不建议为此使用任何框架,因为它实际上是 JavaScript 中的一个简单检查。

回答by iSkore

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

使用或不使用 jQuery,有三种“普通”方法可以检查这一点。

  1. First 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 typeofcheck:

    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;
    }
    
  1. 首先是通过强制强制布尔评估,然后检查它是否等于原始值:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  2. 做一个简单的typeof检查:

    function isBoolean( n ) {
        return typeof n === 'boolean';
    }
    
  3. 在原始对象上对类包装器进行完全矫枉过正和不必要的实例化:

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

The third will only return trueifyou create a new Booleanclass and pass that in.

第三个只会true您创建一个new Boolean类并将其传入时返回。

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;
    }
    
  • Boolean

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

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

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

回答by Morry

You can use pure Javascript to achieve this:

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

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

回答by Willem Franco

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;
}

回答by Volodymyr Frolov

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 truereturns "boolean"while typeof new Boolean(true)returns "object".

这种复杂化的原因是typeof true返回"boolean"whiletypeof new Boolean(true)返回"object"

回答by Marcus Junius Brutus

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

我会选择 Lodash:isBoolean检查传入的变量是原始布尔值还是布尔值包装对象,因此可以考虑所有情况。

回答by Mohsen Kadoura

You can create a function that checks the typeoffor an argument.

您可以创建一个函数来检查typeof参数。

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

回答by Imam Kuncoro

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

有时我们需要一种方法来检查它。typeof 不适用于日期等。所以我让它变得容易

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

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

也为NumberStringBoolean等我们经常需要检查的类型在一个单一的方式...