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

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

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

但这对我来说不太好。

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


当前回答

判断真假最简单的方法是: (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");

其他回答

基准:

都很相似……

const { performance } = require('perf_hooks');

const boolyah = true;
var t0 = 0;
var t1 = 0;
const loops = 1000000;
var results = { 1: 0, 2: 0, 3: 0, 4: 0 };

for (i = 0; i < loops; i++) {

    t0 = performance.now();
    boolyah === false || boolyah === true;
    t1 = performance.now();
    results['1'] += t1 - t0;

    t0 = performance.now();
    'boolean' === typeof boolyah;
    t1 = performance.now();
    results['2'] += t1 - t0;

    t0 = performance.now();
    !!boolyah === boolyah;
    t1 = performance.now();
    results['3'] += t1 - t0;

    t0 = performance.now();
    Boolean(boolyah) === boolyah;
    t1 = performance.now();
    results['4'] += t1 - t0;
}

console.log(results);

  // RESULTS
  // '0': 135.09559339284897,
  // '1': 136.38034391403198,
  // '2': 136.29421120882034,
  // '3': 135.1228678226471,
  // '4': 135.11531442403793

在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”。

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

我会使用Lodash: isBoolean检查传入的变量是基元布尔型还是布尔型包装对象,因此可以解释所有情况。

创建像isBoolean这样的函数,它包含了一个线性typeof v === "boolean",从长远来看似乎非常不方便。我很惊讶几乎每个人都建议创建自己的函数。这似乎与扩展原生原型是一样的癌症。

您需要在参与的每个项目中重新创建它们 其他开发人员可能有不同的习惯,或者需要检查您的函数的源代码,以查看您使用的检查的实现,以了解您的检查的弱点 你会感到沮丧,当你试图写一行在控制台现场不属于你的项目

记住typeof v === "boolean"就行了。 在IDE中添加一个模板,这样就可以通过一些三个字母的快捷方式来放置它。