Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3619
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  花落未央
    2020-11-22 00:22

    You may find the following function useful:

    function typeOf(obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
    }
    

    Or in ES7 (comment if further improvements)

    function typeOf(obj) {
      const { toString } = Object.prototype;
      const stringified = obj::toString();
      const type = stringified.split(' ')[1].slice(0, -1);
    
      return type.toLowerCase();
    }
    

    Results:

    typeOf(); //undefined
    typeOf(null); //null
    typeOf(NaN); //number
    typeOf(5); //number
    typeOf({}); //object
    typeOf([]); //array
    typeOf(''); //string
    typeOf(function () {}); //function
    typeOf(/a/) //regexp
    typeOf(new Date()) //date
    typeOf(new WeakMap()) //weakmap
    typeOf(new Map()) //map
    

    "Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.

提交回复
热议问题