JavaScript判断对象是否为空对象

1、使用json

let obj1 = {
    
    }, obj2 = {
    
    name: 'bob'}
const isEmpty = JSON.parse()
let isEmpty1 = JSON.stringify(obj1) === '{}' // isEmpty1 -> true
let isEmpty2 = JSON.stringify(obj2) === '{}' // isEmpty2 -> false

2、使用forIn循环

let obj1 = {
    
    },obj2 = {
    
    name: 'bob'}
function isEmpty(object){
    
    
    for(let key in object){
    
    

        return false
    }
    return true
}

console.log(isEmpty(obj1)) // true
console.log(isEmpty(obj2)) //false

3、通过jquery的isEmptyObject()方法,其本质是forin循环

let obj1 = {
    
    }, obj2 = {
    
    name: 'bob'}
const isEmpty1 = $.isEmptyObject(obj1) // true
const isEmpty2 = $.isEmptyObject(obj2) // false

4、通过Object.getOwnPropertyNames(),此方法不兼容ie8

let obj1 = {
    
    }, obj2 = {
    
    name: 'bob'}
const isEmpty1 = Object.getOwnPropertyNames(obj1).length === 0 // true
const isEmpty2 = $.isEmptyObject(obj2).length === 0 // false

5、通过ES6的Object.keys(),与Object.getOwnPropertyNames()相似

let obj1 = {
    
    }, obj2 = {
    
    name: 'bob'}
const isEmpty1 = Object.keys(obj1).length === 0 // true
const isEmpty2 = $.keys(obj2).length === 0 // false

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/121414868