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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With