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

前端 未结 30 3581
眼角桃花
眼角桃花 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:15

    For everyone coming here for having similar question, the following works great and I have it in my library the last years:

    (function(g3, $, window, document, undefined){
       g3.utils = g3.utils || {};
    /********************************Function type()********************************
    * Returns a lowercase string representation of an object's constructor.
    * @module {g3.utils}
    * @function {g3.utils.type}
    * @public
    * @param {Type} 'obj' is any type native, host or custom.
    * @return {String} Returns a lowercase string representing the object's 
    * constructor which is different from word 'object' if they are not custom.
    * @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
    * http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
    * http://javascript.info/tutorial/type-detection
    *******************************************************************************/
    g3.utils.type = function (obj){
       if(obj === null)
          return 'null';
       else if(typeof obj === 'undefined')
          return 'undefined';
       return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
    };
    }(window.g3 = window.g3 || {}, jQuery, window, document));
    

提交回复
热议问题