手写一个判断空值的函数

空数组,空对象,空格字符串,undefined,null都算空值

js
12345678910111213141516171819202122232425
function isEmpty(value) {
 //1、判断空字符串
    if(type value === "string"){
        if(value.trim().length === 0)return true
    }
 //2、判断空数组
    if(Array.isArray(value)){
        if(value.length === 0)return true
    }
 //3、判断null和undefined
    if(value === null || value === undefined)return true
 //4、判断空对象
    if(typeof value === "object"){
        if(Object.keys(value).length === 0)return true
    }
    return false
}

// 测试用例:
console.log(isEmpty(""));        // true
console.log(isEmpty("   "));     // true (纯空格字符串)
console.log(isEmpty({}));        // true (空对象)
console.log(isEmpty([]));        // true (空数组)
console.log(isEmpty(null));      // true
console.log(isEmpty(0));         // false (数字0通常算有效值)