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

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

当前回答

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

其他回答

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

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

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

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

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

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

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

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

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

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

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

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

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

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