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

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

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

但这对我来说不太好。

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


当前回答

更新:以前的解决方案是更具体的,你可以选择哪个值你想考虑作为一个布尔值,你可以添加在正则表达式,如果你需要一个更通用的解决方案,不想添加一个库,然后检查下面的解决方案(从lodash的布尔)

function getTag(value) {
  if (value == null) {
    return value === undefined ? '[object Undefined]' : '[object Null]'
  }
  return toString.call(value)
}

function isObjectLike(value) {
  return typeof value === 'object' && value !== null
}

function isBoolean(value) {
  return value === true || value === false ||
    (isObjectLike(value) && getTag(value) == '[object Boolean]')
}

之前的解决方案 const isBoolean = (val) => { const boolValuesRegex = /true|false/// Add other /true|false|1|0|on|off/ 如果(val === undefined || val === null)返回false; .toLowerCase返回boolValuesRegex.test (val.toString () ()); } 常量值=(真的,假的,“真正的”,“假”,“真正的”,“假”,“sampletext”,1,定义,null , (() => {}), {}, []]; document.body.innerHTML = values。map(x => ' ${x} - ${isBoolean(x)} ') .join('</br>');

其他回答

有时我们只需要一种方法来检验。Typeof不能用于date等。所以我用

Date.prototype.getType() { return "date"; }

此外,对于数字,字符串,布尔等,我们经常需要以单一的方式检查类型…

这就是typeof存在的意义。括号是可选的,因为它是一个操作符。

if (typeof variable == "boolean") {
    // variable is a boolean
}

判断真假最简单的方法是: (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
if(['true', 'yes', '1'].includes(single_value)) {
    return  true;   
}
else if(['false', 'no', '0'].includes(single_value)) {
    return  false;  
}

如果你有一个字符串