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

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

当前回答

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

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

其他回答

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

var ? function_if_exists() : function_if_doesnt_exist();

对于我的用例,大多数现有答案都失败了,如果将函数分配给变量或返回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},函数(){}

我想这会让你的代码看起来更简单

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false

根据jAndy的回答,如果该值为以下任一值,那么如果您想避免为真:

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

一种可能避免获得真实值的解决方案如下:

function isUsable(valueToCheck) {
    if (valueToCheck === 0     || // Avoid returning false if the value is 0.
        valueToCheck === ''    || // Avoid returning false if the value is an empty string.
        valueToCheck === false || // Avoid returning false if the value is false.
        valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
    {
        return true;
    } else {
        return false;
    }
}

其用途如下:

if (isUsable(x)) {
    // It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
    // It is NOT usable!
}

除这些情况外,如果对象或数组为空,则可能需要返回false:

对象:{}(使用ECMA7+)阵列:[](使用ECMA 5+)

你可以这样做:

function isEmptyObject(valueToCheck) {
    if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
        // Object is empty!
        return true;
    } else {
        // Object is not empty!
        return false;
    }
}

function isEmptyArray(valueToCheck) {
    if(Array.isArray(valueToCheck) && !valueToCheck.length) {
        // Array is empty!
        return true;
    } else {
        // Array is not empty!
        return false;
    }
}

如果希望检查所有空白字符串(“”),可以执行以下操作:

function isAllWhitespace(){
    if (valueToCheck.match(/^ *$/) !== null) {
        // Is all whitespaces!
        return true;
    } else {
        // Is not all whitespaces!
        return false;
    }
}

注意:如果变量被声明为空字符串中的任何一个,hasOwnProperty对于空字符串(0、false、NaN、null和undefined)返回true,因此这可能不是最好的用法。可以修改该函数以使用它来显示它已声明,但不可用。

你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。