Reputation: 475
I'm new to JS and Query so I think it's a very simple task, I would like just for a test rewrite "loop" from $.each() to $().each() and for loop. This is my code.
var tab = ["John", "Steve", "Ben", "Damon", "Ian"],
$list = $('#list');
$.each(tab,function(index,value){
$list.append("<li>"+ value+ "</li>");
});
Second and third loops don't work:
tab.each(function(index){
$list.append("<li>"+ tab[index] + "</li>");
});
and
for (var i,len=tab.length;i<len;i++) {
$list.append("<li>"+ tab[i]+ "</li>");
}
What is wrong?
Upvotes: 0
Views: 1834
Reputation: 167172
Error in correct initialization of for
loop:
for (var i,len=tab.length;i<len;i++) {
//-------^ - Missing inital value.
$list.append("<li>"+ tab[i]+ "</li>");
}
Change to:
for (var i=0,len=tab.length;i<len;i++) {
$list.append("<li>"+ tab[i]+ "</li>");
}
Second one doesn't work because, tab
is not a jQuery object to iterate! :)
The syntax of $.each
is either:
$.each(dataArray, function() { });
Or, if you have a DOM jQuery object:
$(Selector).each(dataArray, function() { });
Upvotes: 5
Reputation: 1684
Wrap your JS array to become a jQuery object for beeing able to call each on it:
$(tab).each(function(){
$list.append("<li>"+ this + "</li>")
})
and initialize your running variable with zero (i=0), furthermore for readability reasons you should not store the tab.length into a temporary variable:
for(var i=0; i<tab.length; i++) {
$list.append("<li>"+ tab[i]+ "</li>")
}
Upvotes: 0
Reputation: 41
Try this,
var tab = ["John", "Steve", "Ben", "Damon", "Ian"];
for(i=0;i<=tab.length;i++)
{
alert(tab[i]);
}
Upvotes: 0
Reputation: 28548
As per documentation of jQuery:
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.)
Also see here:
Here's what you need to remember:
Upvotes: 0
Reputation: 1898
If you are iterating over a Javascript array, not a jQuery selection, you have to use $.each, that is the way that it works.
As for your third example, i needs to be initialized with 0. Otherwise it is undefined which is always false when comparing to the length of the array.
Upvotes: 0
Reputation: 1087
You need to change as var i=0, len=tab.length
in
for (var i,len=tab.length;i<len;i++) {
$list.append("<li>"+ tab[i]+ "</li>");
}
Upvotes: 1