JQuery.each () undefined problem

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
   }
}

I warn about the length of the elements, there are elements in it (more precisely, 11). since 11 elements could be present, but jQuery still passes undefined?

+3
source share
3 answers

The only explanation for this is that the array of elements contains values ​​that are undefined, ie:

items = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];

Both other answers are completely incorrect. The first parameter eachis the index, not the value, and jQuery.fn.each calls jQuery.each. There is no meaning between them.

+6
source

, jQuery wrappet set . a array object jQuery helper function $. each()

$.each(items, function(index, element){
});

, .each() javascripts native for..in.

arrays, for loop.

, jQuery constructor . , , , 95% jQuery, / .

+5

... (?):

. CSS-, :

var foo = { x: 10, y: 12 }; 

$(foo).animate({ x: "+=20", y: "20" }, 1000, 
      function () { alert(foo.x + ":" + foo.y); }); 

"30:20". ? , .:)

Array trick - you set the same property for each record. Example:

var foo = [{ x: 10 }, { x: 20 }]; 

$(foo).animate({ x: "+=30" }, 1000, 
      function () { alert(this.x); }); 

Pops out "40" and "50".

0
source

Source: https://habr.com/ru/post/1756450/


All Articles