首页 文章

是否有一个标准函数来检查JavaScript中的null,undefined或blank变量?

提问于
浏览
1733

是否有一个通用的JavaScript函数来检查变量是否有值并确保它不是 undefinednull ?我've got this code, but I'我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

30 回答

  • 0

    虽然是老人,但忘记的是他们应该包装他们的代码块然后捕获错误然后测试...

    function checkup( t ){
      try{
        for(p in t){
          if( p.hasOwnProperty( t ) ){
            return true;
          }
        }
        return false;
      }catch(e){
        console.log("ERROR : "+e);
        return e;
      }
    }
    

    所以你真的不必事先检查潜在的问题,你只需 grab 它然后按照你想要的方式处理它 .

  • 2

    如果未声明变量,则无法使用函数测试未定义,因为您将收到错误 .

    if (foo) {}
    function (bar) {}(foo)
    

    如果没有声明foo,两者都会产生错误 .

    如果要测试是否已声明变量,则可以使用

    typeof foo != "undefined"
    

    如果你想测试foo是否已被声明并且它有一个你可以使用的值

    if (typeof foo != "undefined" && foo) {
        //code here
    }
    
  • 3505

    您可以使用:

    If子句验证字符串或值是否为空 . 像这样:

    if (someVar.value) 
    {
      //its not emppty
    }
    else
    {
      //Its empty
    }
    
  • 25

    评分最高的第一个答案是错误的 . 如果value未定义,它将在现代浏览器中引发异常 . 你必须使用:

    if (typeof(value) !== "undefined" && value)
    

    要么

    if (typeof value  !== "undefined" && value)
    
  • 4

    我觉得用的是?操作员稍微清洁一点 .

    var ? function_if_exists() : function_if_doesnt_exist();
    
  • 1

    我知道这是一个老问题,但这是最安全的检查,我没有看到它在这里发布完全相同:

    if (typeof value != 'undefined' && value) {
        //deal with value'
    };
    

    它将涵盖从未定义 value 的情况,以及以下任何一种情况:

    • null

    • undefined(undefined的值与从未定义的参数不同)

    • 0

    • “”(空字符串)

    • NaN

    附: typeof value != 'undefined' 无需严格平等

  • 1

    你有点过头了 . 要检查变量是否未赋值,您只需要检查undefined和null .

    function isEmpty(value){
        return (typeof value === "undefined" || value === null);
    }
    

    这假设 0"" ,并且对象(甚至空对象和数组)有效"values" .

  • 4

    检查默认值

    function typeOfVar (obj) {
          return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
    }
    function isVariableHaveDefaltVal(variable) {
        if ( typeof(variable) === 'string' ) {  // number, boolean, string, object 
            console.log(' Any data Between single/double Quotes is treated as String ');        
            return (variable.trim().length === 0) ? true : false;
        }else if ( typeof(variable) === 'boolean' ) {
          console.log('boolean value with default value \'false\'');
            return (variable === false) ? true : false;
        }else if ( typeof(variable) === 'undefined' ) {
            console.log('EX: var a; variable is created, but has the default value of undefined.'); 
            return true;
        }else if ( typeof(variable) === 'number' ) { 
            console.log('number : '+variable);
            return (variable === 0 ) ? true : false;
        }else if ( typeof(variable) === 'object' ) {
       //   -----Object-----
            if (typeOfVar(variable) === 'array' && variable.length === 0) {
                console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
                return true;
            }else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
                console.log('\t Object String with length = ' + variable.length);
                return true;
            }else if (typeOfVar(variable) === 'boolean' ) {
                console.log('\t Object Boolean = ' + variable);
                return (variable === false) ? true : false;
            }else if (typeOfVar(variable) === 'number' ) {
                console.log('\t Object Number = ' + variable);
                return (variable === 0 ) ? true : false;
            }else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
           console.log('\t Object Regular Expression : ');
            return true;
            }else if (variable === null) {
           console.log('\t Object null value');
            return true;
            }
        }
        return false;
    }
    var str = "A Basket For Every Occasion";
    str = str.replace(/\s/g, "-");
    //The "g" flag in the regex will cause all spaces to get replaced.
    

    检查结果:

    isVariableHaveDefaltVal(' '); // string          
    isVariableHaveDefaltVal(false); // boolean       
    var a;           
    isVariableHaveDefaltVal(a);               
    isVariableHaveDefaltVal(0); // number             
    isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true         
    isVariableHaveDefaltVal(null);              
    isVariableHaveDefaltVal([]);               
    isVariableHaveDefaltVal(/ /);              
    isVariableHaveDefaltVal(new Object(''));               
    isVariableHaveDefaltVal(new Object(false));            
    isVariableHaveDefaltVal(new Object(0)); 
    typeOfVar( function() {} );
    

    我使用@Vix函数()来检查哪种类型的对象 .

    使用instansof«

    var prototypes_or_Literals = function (obj) {
        switch (typeof(obj)) {
            // object prototypes
            case 'object':
                if (obj instanceof Array)
                    return '[object Array]';
                else if (obj instanceof Date)
                    return '[object Date]';
                else if (obj instanceof RegExp)
                    return '[object regexp]';
                else if (obj instanceof String)
                    return '[object String]';
                else if (obj instanceof Number)
                    return '[object Number]';
    
                else
                    return 'object';
            // object literals
            default:
                return typeof(obj);
        }   
    };
    output test «
    prototypes_or_Literals( '' ) // "string"
    prototypes_or_Literals( new String('') ) // "[object String]"
    Object.prototype.toString.call("foo bar") //"[object String]"
    
  • 2

    检查值是未定义还是null的详细方法是:

    return value === undefined || value === null;
    

    您也可以使用 == 运算符,但这需要一个know all the rules

    return value == null; // also returns true if value is undefined
    
  • 7

    这是一个非常简单的问题 .

    if(data) {
      //Comes inside only if the data is not empty and not null 
    }
    
  • 60

    此函数检查 empty object {}empty array []nullundefinedblank string ""

    function isEmpty(val) {
      //check for empty object {}, array []
      if (val !== null && typeof val === 'object') {
        if (Object.keys(obj).length === 0) {
          return true;
        }
      }
      //check for undefined, null and "" 
      else if (val == null || val === "") {
        return true;
      }
      return false;
    }
    

    var val = {}; isEmpty(val) - > true val = []; isEmpty(val) - > true isEmpty(undefined) - > true isEmpty(null) - > true isEmpty(“”) - > true isEmpty(false) - > false isEmpty(0) - > false

  • -3
    return val || 'Handle empty variable'
    

    是一个非常好的和干净的方式来处理它在很多地方,也可以用来分配变量

    const res = val || 'default value'
    
  • 5

    您可以检查变量是否具有 truthy 值 . 这意味着

    if( value ) {
    }
    

    如果 valuenot ,将评估为 true

    • null

    • undefined

    • NaN

    • 空字符串(“”)

    • 0

    以上列表表示ECMA- / Javascript中所有可能的 falsy 值 . 在 ToBoolean 部分的specification中找到它 .

    此外,如果您没有 know 是否存在变量(即,如果已声明),则应使用 typeof 运算符进行检查 . 例如

    if( typeof foo !== 'undefined' ) {
        // foo could get resolved and it's defined
    }
    

    如果您可以确定至少声明了变量,则应直接检查它是否具有如上所示的 truthy 值 .

    进一步阅读:http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

  • 27

    对于我的情况,我尝试使用if null,',!变量,但它没有用 .

    请参阅下面的代码以获取html字段中的文本

    var status=$(this).text(); //for example (for my case)
    

    如果状态变量中没有值(无文本),我试图将值'novalue'设置为状态变量 .

    以下代码有效 .

    if(status == false)
    {
       status='novalue';
    }
    

    当没有找到satus变量的文本时,上面的代码为状态变量分配了“novalue”

  • -1
    var myNewValue = myObject && myObject.child && myObject.child.myValue;
    

    这永远不会抛出错误 . 如果myObject,child或myValue为null,则myNewValue将为null . 不会抛出任何错误

  • 0
    function isEmpty(val){
        return !val;
    }
    

    但是这个解决方案是过度设计的,如果你不想稍后修改函数模型需求,那么在代码中直接使用它是更干净的:

    if(!val)...
    
  • 6
    function isEmpty(obj) {
        if (typeof obj == 'number') return false;
        else if (typeof obj == 'string') return obj.length == 0;
        else if (Array.isArray(obj)) return obj.length == 0;
        else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
        else if (typeof obj == 'boolean') return false;
        else return !obj;
    }
    

    在ES6中使用trim来处理空白字符串:

    const isEmpty = value => {
        if (typeof value === 'number') return false
        else if (typeof value === 'string') return value.trim().length === 0
        else if (Array.isArray(value)) return value.length === 0
        else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
        else if (typeof value === 'boolean') return false
        else return !value
    }
    
  • 11
    function isEmpty(value){
      return (value == null || value.length === 0);
    }
    

    这将返回true

    undefined  // Because undefined == null
    
    null
    
    []
    
    ""
    

    和零参数函数,因为函数 length 是它所采用的声明参数的数量 .

    要禁止后一类,您可能只想检查空字符串

    function isEmpty(value){
      return (value == null || value === '');
    }
    
  • 16

    这是我的 - 如果value为null,undefined等等或空白(即仅包含空格),则返回true:

    function stringIsEmpty(value) {
    
        return value ? value.trim().length == 0 : true;
    
    }
    
  • 9

    您可以使用波纹管代码检查所有四(4)条件进行验证,如非空,非空白,未定义,而不是零只在javascript和jquery中使用此代码(!(!(变量))) .

    function myFunction() {
        var data;  //The Values can be like as null, blank, undefined, zero you can test
    
        if(!(!(data)))
        {
            alert("data "+data);
        } 
        else 
        {
            alert("data is "+data);
        }
    }
    
  • 26

    如果您使用 TypeScript 并且不想占用 "values those are false" ,那么这是您的解决方案:

    第一名: import { isNullOrUndefined } from 'util';

    然后: isNullOrUndefined(this.yourVariableName)

    请注意:如上所述below现已弃用,请改用 value === undefined || value === null . ref .

  • 4

    您可能会发现以下功能有用:

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

    或者在ES7中(如果进一步改进则发表评论)

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

    结果:

    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
    

    “请注意,绑定运算符(::)不是ES2016(ES7)的一部分,也不是ECMAScript标准的任何后续版本 . 它目前是引入该语言的第0阶段(草编)提议 . ” - 西蒙谢尔贝格 . 作者希望加入他对这一美丽提案的支持,以获得皇室提升 .

  • 3

    它可能是有用的 .

    [null, undefined, ''].indexOf(document.DocumentNumberLabel) > -1
    
  • 1

    这种情况检查

    if (!!foo) {
        //foo is defined
    }
    

    是你所需要的全部 .

  • 0

    如果你更喜欢普通的javascript试试这个:

    /**
       * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
       * length of `0` and objects with no own enumerable properties are considered
       * "empty".
       *
       * @static
       * @memberOf _
       * @category Objects
       * @param {Array|Object|string} value The value to inspect.
       * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
       * @example
       *
       * _.isEmpty([1, 2, 3]);
       * // => false
       *
       * _.isEmpty([]);
       * // => true
       *
       * _.isEmpty({});
       * // => true
       *
       * _.isEmpty('');
       * // => true
       */
    
    function isEmpty(value) {
        if (!value) {
          return true;
        }
        if (isArray(value) || isString(value)) {
          return !value.length;
        }
        for (var key in value) {
          if (hasOwnProperty.call(value, key)) {
            return false;
          }
        }
        return true;
      }
    

    否则,如果您已经使用下划线或lodash,请尝试:

    _.isEmpty(value)
    
  • 4

    对于每个来这里有类似问题的人来说,下面的工作很棒,而且我在过去的几年里在我的图书馆里有这个:

    (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));
    
  • 164

    您可以直接使用相等运算符

    <script>
        var firstName;
        var lastName = null;
        /* Since null == undefined is true, the following statements will catch both null and undefined */
            if(firstName == null){
                alert('Variable "firstName" is undefined.');
            }    
            if(lastName == null){
               alert('Variable "lastName" is null.');
            }
    </script>
    

    demo @ How to determine if variable is undefined or null using JavaScript

  • 3

    这将检查是否未定义不确定嵌套的变量

    function Undef(str) 
    {
      var ary = str.split('.');
      var w = window;
      for (i in ary) {
        try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
        catch(e) { return true; }
      }
      return false;
    }
    
    if (!Undef("google.translate.TranslateElement")) {
    

    以上检查是否存在Google翻译功能TranslateElement . 这相当于:

    if (!(typeof google === "undefined" 
     || typeof google.translate === "undefined" 
     || typeof google.translate.TranslateElement === "undefined")) {
    
  • -1

    ! 检查空字符串(“”),null,undefined,false以及数字0和NaN . 比如,如果字符串为空 var name = ""console.log(!name) 返回 true .

    function isEmpty(val){
      return !val;
    }
    

    如果 valempty, null, undefined, false, the number 0 or NaN ,则此函数将返回true .

  • 2
    try{
    
         let vari = obj.propTest; // obj may be don't have propTest property
    
            ...
    } catch(NullException){
        // do something here
    }
    

    我认为使用try catch将避免任何null检查错误,也可以在Angular或JavaScript中捕获null异常和进程 .

相关问题