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

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

当前回答

对于我的用例,大多数现有答案都失败了,如果将函数分配给变量或返回NaN,则大多数答案返回为空。帕斯卡的回答很好。

这是我的实现,请测试并让我知道,如果你发现了什么。你可以在这里看到我是如何测试这个函数的。

function isEmpty(value) {
  return (
    // Null or undefined.
    (value == null) ||
    // Check if a Set() or Map() is empty
    (value.size === 0) ||
    // NaN - The only JavaScript value that is unequal to itself.
    (value !== value) ||
    // Length is zero && it's not a function.
    (value.length === 0 && typeof value !== "function") ||
    // Is an Object && has no keys.
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

退货:

true:undefined,null,“”,[],{},NaN,new Set()//false:true,false,1,0,-1,“foo”,[1,2,3],{foo:1},函数(){}

其他回答

这里是我的-如果值为null、undefined等或空白(即仅包含空格),则返回true:

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}
function isEmpty(obj) {
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
    else return !obj;
}

在ES6中,使用trim处理空白字符串:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}

这是我检查数据是否为空的解决方案。

const _isEmpty = (data) => {
  return (
    // this way we can also check for undefined values. null==undefined is true
    data == null ||
    data == "" ||
    (Array.isArray(data) && data.length === 0) ||
    // we want {} to be false. we cannot use !! because !!{} turns to be true
    // !!{}=true and !!{name:"yilmaz"}=true. !! does not work ofr objects
    (data.constructor === Object && Object.keys(data).length === 0)

  );
};

这还包括空数组和空对象

null,未定义,“”,0,[],{}

isEmpty = (value) => (!value  || (typeof v === 'object' &&
   Object.keys(value).length < 1));

我非常喜欢的解决方案:

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

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}