I have the following code
function myFunction(items) {
// this prints out 11
alert(items.length);
$(items).each(function(i, item) {
// item is undefined for some reason
}
}
It I alert the length of items, it has elements in it (11 to be exact). so how could 11 items be present, but jQuery still pass undefined?
I have the following code
function myFunction(items) {
// this prints out 11
alert(items.length);
$(items).each(function(i, item) {
// item is undefined for some reason
}
}
It I alert the length of items, it has elements in it (11 to be exact). so how could 11 items be present, but jQuery still pass undefined?
Share Improve this question asked Jul 25, 2010 at 17:38 A-DubbA-Dubb 1,7092 gold badges19 silver badges24 bronze badges 2 |3 Answers
Reset to default 8The only explanation for this is the that items array contains values which are undefined, i.e :
items = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
Both of the other answers are wholly incorrect. The first parameter of each
is the index, not the value, and jQuery.fn.each calls jQuery.each. There is no disambiguation between them.
It sounds like you are not passing a jQuery wrappet set
to your function. If you pass
an array
or an object
you need to use the jQuery helper function
$.each() like
$.each(items, function(index, element){
});
As I already mentioned several times in other answers, it is bad practice to loop over an array with .each()
or javascripts native for..in
.
If you are passing arrays
use a standard for loop
.
edit
As it turns out, you actually really can call the jQuery constructor
with a standard array.
But it seems like terrible karma to do so, you can't call 95% of all those jQuery methods, unless you want to crash / corrupt your code.
Since comments don't allow pretty code listings ... (do they?):
Animate will work against anything. It's documented as only working against CSS properties, but just to prove a point:
var foo = { x: 10, y: 12 };
$(foo).animate({ x: "+=20", y: "20" }, 1000,
function () { alert(foo.x + ":" + foo.y); });
Will spit out "30:20". Is this useful? Perhaps not in everyday work. :)
The trick with arrays is you'll set the same property across each entry. Example:
var foo = [{ x: 10 }, { x: 20 }];
$(foo).animate({ x: "+=30" }, 1000,
function () { alert(this.x); });
Spits out "40" and "50".
$(this)
inside of your.each()
callback? Nothing looks incorrect so it would be helpful to see an SSCCE. – Matt Ball Commented Jul 25, 2010 at 17:42items
? is it an array or an array-like object like anHTMLCollection
returned from.getElementsByClassName()
for instance. Either way why not just use a standard for loop? – jasongetsdown Commented Jul 26, 2010 at 19:41