js中判断对象是否为空的五种方法

0.Reflect.ownKeys()

let obj1 = {
    Symbol,
    name: undefined,
    fn: () => { }
}

let obj2 = {
    name: 'll'
}
let obj3 = {}

const check0 = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

console.log(check0(obj1)); //false
console.log(check0(obj2)); //false
console.log(check0(obj3)); //true

1.Object.getOwnPropertyNames()

let obj1 = {
    Symbol,
    name: undefined,
    fn: () => { }
}

let obj2 = {
    name: 'll'
}

let obj3 = {}

const check1 = (obj) => Object.getOwnPropertyNames(obj).length === 0

console.log(check1(obj1)); //false
console.log(check1(obj2)); //false
console.log(check1(obj3)); //true

2.Object.keys()

let obj1 = {
    Symbol,
    name: undefined,
    fn: () => { }
}

let obj2 = {
    name: 'll'
}

let obj3 = {}

const check2 = (obj) => Object.keys(obj).length === 0

console.log(check2(obj1)); //false
console.log(check2(obj2)); //false
console.log(check2(obj3)); //true

3.for...in

let obj1 = {
    Symbol,
    name: undefined,
    fn: () => { }
}

let obj2 = {
    name: 'll'
}

let obj3 = {}

const check3 = (obj) => {
    for (let key in obj) {
        // 如果能遍历
        return false
    }

    // 如果不能遍历
    return true
}

console.log(check3(obj1)); //false
console.log(check3(obj2)); //false
console.log(check3(obj3)); //true

4.JSON.stringfy()  对于 undefined、任意的函数以及 symbol 三个特殊的值分别作为对象属性的值、数组元素、单独的值时 JSON.stringify() 将返回不同的结果。 

let obj1 = {
    Symbol,
    name: undefined,
    fn: () => { }
}

let obj2 = {
    name: 'll'
}

let obj3 = {}

const check4 = (obj) => {
    return JSON.stringify(obj) === "{}"
}

console.log(check4(obj1)); //true
console.log(check4(obj2)); //false
console.log(check4(obj3)); //true

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值