我可以使用 jquery $.each()
从数组中的第 3 项或任何其他项开始循环吗?还有$(elem).each()
.我想要这两个例子。 #tableau
是 <table>
的 ID在 HTML 中。
请参阅下面的代码:
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);
});
非常感谢
最佳答案
除了 0
之外,您不能使用 $.each()
开始,但是您可以通过使用 if( )
语句。
$.each(superMarios, function(i, val){
if( i >= 2 ) {
console.log(i + ': ' + val);
tds.eq(i).append(val);
}
});
或者如果你想从第三个开始,但你希望索引从 0
开始,那么只需取一个数组的 .slice()
,给它是您要开始的从零开始的索引。
$.each(superMarios.slice( 2 ), function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
或者作为第一个示例的替代方案,只需将 i
偏移与起点相同的量即可为您提供更高的起点索引:
var idx = 2;
$.each(superMarios.slice( idx ), function(i, val){
console.log((i+idx) + ': ' + val);
tds.eq(i+idx).append(val);
});
关于javascript - 使用 jquery $.each 从数组中的任何项目位置开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207700/