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

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

当前回答

您可以使用零合并运算符??检查空值和未定义值。参见MDN文档

null ?? 'default string'; // returns "default string"

0 ?? 42;  // returns 0

(null || undefined) ?? "foo"; // returns "foo"

其他回答

虽然是老掉牙,但忘记的是他们应该包装代码块,然后捕捉错误,然后测试。。。

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

因此,你真的不必事先检查潜在的问题,你只需抓住它,然后按照你想要的方式处理它。

您可以只检查变量是否具有真实值。这意味着

if (value) {
    // do something..
}

如果值不是:

无效的未定义NaN公司空字符串(“”)0假的

上面的列表表示ECMA-/Javascript中所有可能的错误值。在ToBoolean部分的规范中找到它。

此外,如果您不知道变量是否存在(也就是说,如果声明了变量),则应使用typeof运算符进行检查。例如

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

如果您可以确定至少声明了一个变量,那么应该直接检查它是否具有如上所示的真实值。

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

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

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

当引用或函数可能未定义或为空时,可选的链接运算符提供了一种简化通过连接对象访问值的方法。

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

可以在可选链接之后使用零合并运算符,以便在未找到任何值时构建默认值:

let customer = {
  name: "Carl",
  details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city