How to check if type is Boolean

前端 未结 16 1801
深忆病人
深忆病人 2020-12-07 10:09

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(         


        
16条回答
  •  生来不讨喜
    2020-12-07 10:31

    There are three "vanilla" ways to check this with or without 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 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.

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

    • Boolean:

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

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

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

提交回复
热议问题