Javascript 从jquery$数组中的任意项目位置开始
我可以使用jqueryJavascript 从jquery$数组中的任意项目位置开始,javascript,jquery,html,for-loop,Javascript,Jquery,Html,For Loop,我可以使用jquery$.each()和$(elem.each()从第三个项目或任何其他项目开始循环吗。我想要两个例子#tableau是HTML中的id。 请参见下面的我的代码: var tableau = $('#tableau'), tds = tableau.find('td'), tdLen = tds.length, superMarios = [ 'Super Mario Bros',
$.each()
和$(elem.each()
从第三个项目或任何其他项目开始循环吗。我想要两个例子#tableau
是HTML中
的id。
请参见下面的我的代码:
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);
});
虽然您不能告诉$。每个都从某个索引开始,但可以在将数组传递给$之前先创建数组。每个:
$.each(superMarios.slice(2), function(i, val){
console.log(i + ': ' + val);
tds.eq(i).append(val);
});
注意:切片
不会影响原始阵列。相反,它将返回数组的一部分的副本。+1。我同意jQuery.each()
只应在比原生for
循环更好或更方便时使用。在这种情况下,它不是更好,因此直接控制起点的本机for
循环在这里肯定更好。我来这里是为了建议切片
方法。