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

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

当前回答

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

函数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));

其他回答

我认为使用?操作员稍微干净一点。

var ? function_if_exists() : function_if_doesnt_exist();

我非常喜欢的解决方案:

让我们定义一个空变量为空或未定义,或者如果它有长度,它为零,或者如果是一个对象,它没有键:

function isEmpty (value) {
  return (
    // null or undefined
    (value == null) ||

    // has length and it's zero
    (value.hasOwnProperty('length') && value.length === 0) ||

    // is an Object and has no keys
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

退货:

true:undefined,null,“”,[],{}false:true,false,1,0,-1,“foo”,[1,2,3],{foo:1}

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

函数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 isEmpty(value){
  return (value == null || value.length === 0);
}

对于

undefined  // Because undefined == null

null

[]

""

和零参数函数,因为函数的长度是它所使用的声明参数的数量。

要禁止后一个类别,您可能只需要检查空白字符串

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

Null或空白

function isEmpty(value){
  return (value == null || value.trim().length === 0);
}

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

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