2016-11-11 1 views

Antwort

2

Erste Option

var a = null; 

Zweite Option

if (a !==null && JSON.stringify(a) !== '{}') {..} 
2

function isEmptyObject(obj) { 
 
    return Object.keys(obj).length == 0; 
 
} 
 

 
var a = {}; 
 

 
if (isEmptyObject(a)) { 
 
    console.log('emptyOject') 
 
}

+0

Was ist, wenn a null oder undefiniert ist? Sollte es in Funktion testen. – Will

+0

@will Nicht in einer Funktion namens 'isEmptyObject', wenn Sie sie dann in' isNullOrEmptyObject() 'ändern, aber das Beispiel des OPs handelt von einem leeren Objekt. 'Ich habe eine Variable var a = {};' In jedem Fall ist das trivial ... Ich bin sicher, dass das OP das herausfinden kann. –

1

jQuery tut

function isEmptyObject(obj) { 
    var name; 
    for (name in obj) { 
     return false; 
    } 
    return true; 
} 
+0

Das wird auch vererbte Eigenschaften überprüfen. Solange das OP das von ihnen gewünschte versteht und auswählt. –

0

In ECMA-Script 5

var objInTest = {}; 

function isEmpty(obj) { 
    return Object.keys(obj).length === 0; 
} 

Pre ECMA-Script 5

function isEmpty(obj) { 
    for(var prop in obj) { 
     if(obj.hasOwnProperty(prop)) 
      return false; 
    } 
    return true; 
} 
Verwandte Themen