// 为空方法有很多 只取了一种
// 判断字符串是否为空
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
字符串、数组、对象判断是否为空
最新推荐文章于 2024-04-16 11:42:42 发布