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

我的意思是,有一些替代方案,比如:

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

但这对我来说不太好。

有没有更清洁的方式来实现这个目标?


当前回答

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

其他回答

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

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

关于es2015箭头函数的另一个决策

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

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

造成这种复杂性的原因是typeof true返回“boolean”,而typeof new boolean (true)返回“object”。

判断真假最简单的方法是: (typeof value === "boolean"), 但如果value是布尔类的实例,则返回"object"。因此,为了处理这个问题,我们必须添加另一个条件来检查是否: (value instanceof Boolean)

代码片段:

const value = false;
//const value = new Boolean(10);
//const value = new Boolean("hi");

if((typeof value === "boolean") || (value instanceof Boolean))
    console.log("boolean");
else
    console.log("not boolean");

在nodejs中,通过使用node-boolify,我们可以使用isBoolean();

        var isBoolean = require('node-boolify').isBoolean;
        isBoolean(true); //true
        isBoolean('true'); //true
        isBoolean('TRUE'); //false
        isBoolean(1); //true
        isBoolean(2); //false
        isBoolean(false); //true
        isBoolean('false'); //true
        isBoolean('FALSE'); //false
        isBoolean(0); //true
        isBoolean(null); //false
        isBoolean(undefined); //false
        isBoolean(); //false
        isBoolean(''); //false