2011-05-20 12 views

Respuesta

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

Solo en los navegadores más recientes. Para el registro, la propiedad de las claves solo se admite en IE> = 9 [referencia] (http://kangax.github.io/compat-table/es5/) –

10

Como no tiene atributos, un bucle for no tendrá nada que iterar. Para dar crédito donde es debido, encontré esta sugerencia here.

function isEmpty(ob){ 
    for(var i in ob){ return false;} 
    return true; 
} 

isEmpty({a:1}) // false 
isEmpty({}) // true 
+1

Crearía una función de conteo (obj) e isEmpty evaluaría si el conteo es igual a 0. –

+5

Es posible que desee verificar 'obj.hasOwnProperty (i)' antes de devolver falso. Esto filtra las propiedades heredadas a través de la cadena de prototipos. –

1

Habría que comprobar que se trataba del tipo de 'objeto' de este modo:

(typeof(d) === 'object')

y luego implementar una función corta 'tamaño' para comprobar que está vacío, as mentioned here.

19

Se podría extender Object.prototype con este método isEmpty para comprobar si un objeto no tiene propiedades propias:

Object.prototype.isEmpty = function() { 
    for (var prop in this) if (this.hasOwnProperty(prop)) return false; 
    return true; 
}; 
+17

Wow ...Me parece bastante interesante que javascript carece de esta funcionalidad "básica" – harijay

+1

Extender el Object.prototype puede crear problemas iterando sobre el objeto más adelante http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ –

+0

¡Esto interfiere con la solución genial de jquery –

0

Si intenta esto en Node.js utilizar este fragmento, basado en el código here

Object.defineProperty(Object.prototype, "isEmpty", { 
    enumerable: false, 
    value: function() { 
      for (var prop in this) if (this.hasOwnProperty(prop)) return false; 
      return true; 
     } 
    } 
); 
8

Esto es lo que usa jQuery, funciona muy bien. Aunque esto requiere el script jQuery para usar isEmptyObject.

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

//Example 
var temp = {}; 
$.isEmptyObject(temp); // returns True 
temp ['a'] = 'some data'; 
$.isEmptyObject(temp); // returns False 

Si incluir jQuery no es una opción, simplemente cree una función javascript pura separada.

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

//Example 
var temp = {}; 
isEmptyObject(temp); // returns True 
temp ['b'] = 'some data'; 
isEmptyObject(temp); // returns False 
9

¿Qué le parece usar jQuery?

$.isEmptyObject(d) 
2

Estoy lejos de ser un erudito de JavaScript, pero el siguiente trabajo?

if (Object.getOwnPropertyNames(d).length == 0) { 
    // object is empty 
} 

Tiene la ventaja de ser una llamada de función pura de una línea.

+0

! en realidad es el único sin bucles y sin invocar bibliotecas de terceros –

1
var SomeDictionary = {}; 
if(jQuery.isEmptyObject(SomeDictionary)) 
// Write some code for dictionary is empty condition 
else 
// Write some code for dictionary not empty condition 

Esto funciona bien.

0

Si el rendimiento no es una consideración, este es un método simple que es fácil de recordar:

JSON.stringify(obj) === '{}' 

Es obvio que no quieren ser stringifying objetos de gran tamaño en un bucle, sin embargo.

Cuestiones relacionadas