Probably the most contributing factor for this question is that I am extremely sleepy right now.
I have an array, which I initiate:
var cells = [];
Then i put some values in it (jQuery objects), for example:
$("td").each(function () {
var td = $(this);
cells[td.attr("id")] = td;
});
And now my problem. This code:
$(cells).each(function (i) {
console.log(this) // firebug console
});
logs absolutelly nothing. When i changed the associative array to a normal, number index one by substituting
cells[td.attr("id")] = td;
with
cells.push(td);
It worked correctly.
Also, when I try to iterate with the for..in loop it works as expected.
for (var cell in cells) {
console.log(cells[cell]);
}
Doeas that mean that jQuery’s .each method does not accept associative arrays or am I doing something wrong?
JavaScript does not have associative arrays. It has Arrays and it has Objects, and arrays happen to be objects. When you do this:
..you’re actually doing the equivalent of this:
That is to say you’re actually adding a property called
footo the objecta, not adding an element to the arraya.From the documentation for
jQuery.each():Since you created an
Array([]) jQuery looks at itslengthproperty, and since you have not added any elements to the array (only properties on the object, remember) itslengthis still zero and so jQuery (correctly) does nothing.What you want to do instead, as others have noted, is create an Object using e.g.
var cells = {};. Since a non-Array object has nolengthproperty (not by default, anyway) jQuery will know that you really want to iterate over its properties instead of numeric indices as in an Array.