字符串、数组、对象判断是否为空

// 为空方法有很多 只取了一种
// 判断字符串是否为空
const str = ""
const strIsEmpty = str.length > 0
// 字符串长度大于0  为非空字符串 否则为空字符串

// 判断数组是否为空
const list = []
const listIsEmpty = list.length > 0
// 数组长度大于0  为非空数组  否则为空数组

// 判断对象是否为空
const obj = {}
const keysList = Object.keys({}) // => []
const objIsEmpty = keysList.length > 0 
// keys数组长度大于0  为非空对象  否则为空对象

// 为空方法
const isEmpty = target => {
    const res = Object.prototype.toString.call(target)
    if (res === "[object Object]") {
        return !(Object.keys(target).length > 0)
    }
    if (res === "[object Array]" || res === "[object String]") {
        return !(target.length > 0)
    }
}

console.log(isEmpty({})) // true
console.log(isEmpty([])) // true
console.log(isEmpty("")) // true
console.log(isEmpty({a: 2, b:3})) // false
console.log(isEmpty([1,2])) // false
console.log(isEmpty("asdf")) // false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值