jQuery each()
Here’s something I wasn’t aware of, if an associated array is populated by a named key, the length is not increased.
var someArray = new Array();
someArray['someKey'] = "someValue";
alert(someArray.length); // expected 1, got blank
alert(someArray['someKey']); // "someValue"
This is a problem if you’re trying to loop the array by jQuery.each(arr, function).
// Same array population
$.each(someArray, function(k,v) {
alert(k + "|" + v);
});
This will not do anything as jQuery loops by the array length. Given the way our array is set, this WILL work:
// Same array population
for(var k in someArray) {
alert(k + "|" + someArray[k]);
}
If we change our array to ditch the named key…
var someArray = new Array();
someArray.push("someValue");
$.each(someArray, function(k,v) {
alert(k + "|" + v);
});
That will work, but that isn’t how I want to do it. This is where I was spacing another method, creating an object instead of an array.
var someArray = new Object();
someArray['someKey'] = "someValue";
$.each(someArray, function(k,v) {
alert(k + "|" + v);
});
Ah ha! That’s how to rock it.
jQuery.each docs
There are no comments yet, add one below.