Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
A-Dubb Avatar asked Jul 25 '10 17:07

A-Dubb


People also ask

Why I get undefined in jQuery?

Common causes of 'jQuery is undefined'Incorrect load order of JavaScript assets. jQuery source can't be loaded/found. Conflicting plugins/libraries/code. Framework implementation issues.

What does undefined mean in jQuery?

The jQuery undefined is a primitive value that specifies that a variable has not been initialized a value or may not be declared as well. The jQuery undefined is a built-in primitive data type in jQuery.

Is undefined jQuery error?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.


2 Answers

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

like image 79
Matt Avatar answered Oct 22 '22 14:10

Matt


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.

like image 28
jAndy Avatar answered Oct 22 '22 15:10

jAndy