Doing:
var tags = ["foobar", "hello", "world"];
$.each(tags, function(tag) {
console.log(tag);
});
Gives me an output of
0
1
2
Why is my output not
foobar
hello
world
JSFiddle
The jQuery.each () method is a static method of the jQuery object. It is a more generalized method that can be used to iterate over any object, array or array-like object. So the syntax is quite simple: The OBJECT argument is any object, array or array-like object.
Iterating over jQuery and non-jQuery Objects. jQuery provides an object iterator utility called $.each() as well as a jQuery collection iterator: .each(). These are not interchangeable. In addition, there are a couple of helpful methods called $.map() and .map() that can shortcut one of our common iteration use cases.
Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. The array or array-like object to iterate over.
Note that $.each () is for plain objects, arrays, array-like objects that are not jQuery collections. This would be considered incorrect: For jQuery collections, use .each (). .each () is used directly on a jQuery collection.
Do this, the first parameter is for index:
$.each(tags, function(index, tag) {
console.log(tag);
});
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