How to check if type is Boolean

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

    BENCHMARKING:

    All pretty similar...

    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
    

提交回复
热议问题