gpt4 book ai didi

javascript - 使用 jquery $.each 从数组中的任何项目位置开始

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:13 25 4
gpt4 key购买 nike

我可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com