Can I start looping from the 3rd item, or any other item, in an array with the jquery $.each()
and also with $(elem).each()
. I want both examples. #tableau
is the id of a <table>
in HTML.
See my code below:
var tableau = $('#tableau'),
tds = tableau.find('td'),
tdLen = tds.length,
superMarios = [
'Super Mario Bros',
'Super Mario Bros 2',
'Super Mario Bros 3',
'Super Mario World',
'Super Mario World 2: Yoshi\'s Island',
'Super Mario Galaxy',
'New Super Mario Bros Wii',
'Super Mario Galaxy 2'
],
superMarioCollection = superMarios.length;
$.each(superMarios, function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
Many Thanks
Can I start looping from the 3rd item, or any other item, in an array with the jquery $.each()
and also with $(elem).each()
. I want both examples. #tableau
is the id of a <table>
in HTML.
See my code below:
var tableau = $('#tableau'),
tds = tableau.find('td'),
tdLen = tds.length,
superMarios = [
'Super Mario Bros',
'Super Mario Bros 2',
'Super Mario Bros 3',
'Super Mario World',
'Super Mario World 2: Yoshi\'s Island',
'Super Mario Galaxy',
'New Super Mario Bros Wii',
'Super Mario Galaxy 2'
],
superMarioCollection = superMarios.length;
$.each(superMarios, function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
Many Thanks
Share Improve this question asked Aug 26, 2011 at 16:18 ShaozShaoz 10.7k26 gold badges75 silver badges100 bronze badges3 Answers
Reset to default 4You can't start from anything but 0
with $.each()
, but you can prevent the code inside from running by using an if()
statement.
$.each(superMarios, function(i, val){
if( i >= 2 ) {
console.log(i + ': ' + val);
tds.eq(i).append(val);
}
});
Or if you want to start on the third, but you want the indices to start with 0
, then just take a .slice()
of the Array, giving it the zero-based index where you want to begin.
$.each(superMarios.slice( 2 ), function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
Or as an alternate to the first example, just offset the i
the same amount as your starting point to give you the higher starting index:
var idx = 2;
$.each(superMarios.slice( idx ), function(i, val){
console.log((i+idx) + ': ' + val);
tds.eq(i+idx).append(val);
});
No.
Instead, you should use an ordinary for
loop.
While you cannot tell $.each
to start at a certain index, you can slice
your array before passing it to $.each
:
$.each(superMarios.slice(2), function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
Note: slice
will not effect your original array. Rather, it'll return a copy of a portion of your array.