How to check if type is Boolean

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

提交回复
热议问题