Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() not iterating over array of strings as expected

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

like image 566
xbonez Avatar asked Jan 10 '13 06:01

xbonez


People also ask

How to iterate over an array in jQuery?

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.

How do I iterate over a non-jQuery 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.

How do you iterate over an array in Python?

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.

What is the difference between each () and $each () in jQuery?

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.


1 Answers

Do this, the first parameter is for index:

$.each(tags, function(index, tag) {  
  console.log(tag);
});
like image 151
Sang Suantak Avatar answered Oct 10 '22 20:10

Sang Suantak