Comment tester si un objet est une collection qui peut accepter .each () dans jQuery?
Merci d'avance!
S'il s'agit d'un objet jQuery, vous pouvez toujours utiliser la méthode .each
, même s'il n'y a pas d'éléments. Si l'objet jQuery est vide, il n'entrera plus dans la boucle, il est donc inoffensif d'appeler .each
sur un objet jQuery vide:
obj.each(function(){ ... });
Si vous souhaitez vérifier s'il existe des éléments dans un objet jQuery, vous pouvez utiliser la propriété length
.
if (obj.length > 0) { ... }
Si vous voulez vérifier si un objet est un tableau, afin que vous puissiez l'utiliser dans la méthode $.each
, vous pouvez utiliser la méthode $.isArray
:
if ($.isArray(obj)) { $.each(obj, function(index, value){ ... }); }
Vous pouvez utiliser $.each
pour boucler les propriétés de n'importe quel objet. Vous pouvez utiliser isEmptyObject
pour vérifier s'il existe des propriétés:
if (!$.isEmptyObject(obj)) { $.each(obj, function(key, value){ ... }); }
Vous pouvez utiliser la méthode isPlainObject
pour déterminer si un objet est créé en utilisant un new Object()
ou un objet littéral { ... }
:
if ($.isPlainObject(obj)) { $.each(obj, function(key, value){ ... }); }
Il suffit de tester si l'objet possède each
, ou s'il s'agit d'un object
:
if (obj) { if (typeof obj.each == 'function') { obj.each(function(i,e) { ... }); } else if (typeof obj == 'object') { $.each(obj, function(i,e) { ... }); } else { //alert("not a valid collection"); } } else { //alert("obj is null"); }
Il n'y a pas grand-chose à faire plus de validation, each
s'occupera du reste.