是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

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

当前回答

function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

它还将检查空格(“”)以及以下内容:

null,未定义,NaN,空,字符串(“”),0,false

其他回答

var myNewValue = myObject && myObject.child && myObject.child.myValue;

这永远不会抛出错误。如果myObject、child或myValue为空,则myNewValue将为空。不会引发任何错误

可以使用参数成为数组的参数滤器

函数validateAttributes(arg1、arg2、arg3、arg4){var args=对象.values(参数);return(args.filter(x=>x===null||!x))。长度<=0}console.log(validateAttributes('1',2,3,4));console.log(validateAttributes('1',2,3,null));console.log(validateAttributes('1',未定义,3,4));console.log(validateAttributes('1',2,'',4));console.log(validateAttributes('1',2,3,null));

对于每一个有类似问题的人来说,以下内容非常有用,我在过去的几年里都把它放在了我的图书馆里:

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

可以直接使用相等运算符

<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@如何使用JavaScript确定变量是否未定义或为空

此函数检查空对象{}、空数组[]、空、未定义和空字符串“”

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)->trueval=[];isEmpty(val)->trueisEmpty(未定义)->trueisEmpty(null)->trueisEmpty(“”)->trueisEmpty(false)->falseisEmpty(0)->false