简体   繁体   中英

jQuery.each() undefined issue

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?

The only explanation for this is the that items array contains values which are undefined, ie :

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM