How to check if type is Boolean

前端 未结 16 1744
深忆病人
深忆病人 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:45

    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...

    0 讨论(0)
  • 2020-12-07 10:49

    You can use pure Javascript to achieve this:

    var test = true;
    if (typeof test === 'boolean')
       console.log('test is a boolean!');
    
    0 讨论(0)
  • 2020-12-07 10:49
    if(['true', 'yes', '1'].includes(single_value)) {
        return  true;   
    }
    else if(['false', 'no', '0'].includes(single_value)) {
        return  false;  
    }
    

    if you have a string

    0 讨论(0)
  • 2020-12-07 10:49
    • 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
    0 讨论(0)
提交回复
热议问题