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

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

当前回答

看看新的ECMAScript Nullish合并运算符

你可以想到这个功能-??运算符-作为处理null或undefined时“回退”到默认值的一种方式。

let x = foo ?? bar();

同样,上述代码与以下代码等效。

let x = (foo !== null && foo !== undefined) ? foo : bar();

其他回答

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

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

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

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

这是最安全的支票,我还没有看到它像这样贴在这里:

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

它将涵盖从未定义价值的情况,以及以下任何情况:

无效的undefined(未定义的值与从未定义的参数不同)0“”(空字符串)假的NaN公司

已编辑:更改为严格相等(!==),因为这是现在的标准;)

您可以始终使用loadash函数,例如_.isNil或_.isUndefined。它们非常容易使用。

对于我的案例,我尝试了if null,“”!变量,但它不起作用。

查看下面的代码以从html字段获取文本

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

如果状态变量中没有值(没有文本),我试图将值“novalue”设置为状态变量。

以下代码有效。

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

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