使用.each()从数组中获取索引位置

时间:2014-03-05 16:43:25

标签: jquery

如何检索每个元素的索引位置?:

$(myArray).each(function() {
 console.log( ...this.indexOf()?.... )
}

3 个答案:

答案 0 :(得分:3)

阅读docs。回调的第一个参数是索引。

所以:

$(myArray).each(function(index,item) {
    console.log(index);
});

旁注:Array.forEach以相反的顺序(第一项,然后是索引)获取它的参数,恕我直言,感觉更自然。我不知道为什么jQuery最终会以这种方式提出论据。

答案 1 :(得分:2)

您将获取当前项的索引作为$.each()

的回调函数的第一个参数
$(myArray).each(function(i) {
    console.log(i);
})

演示:Fiddle

答案 2 :(得分:0)

jQuery.each

$(myArray).each(function(index, value) {
 console.log(index);
}
相关问题