0

How do I retrieve the index position of each element?:

$(myArray).each(function() {
 console.log( ...this.indexOf()?.... )
}
1
  • 1
    FYI .each() should be used only for jQuery object relative to DOM nodes, here you should use: $.each(myArray, function(index){console.log(index);}) Commented Mar 5, 2014 at 16:49

3 Answers 3

3

Read the docs. The first argument to your callback is the index.

So:

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

Side note: Array.forEach takes it's arguments in the opposite order (item first, then index) which, IMHO, feels more natural. I have no idea why jQuery ended up putting the arguments that way around.

Sign up to request clarification or add additional context in comments.

Comments

2

You will get the index of the current item as the first argument to the callback function of $.each()

$(myArray).each(function(i) {
    console.log(i);
})

Demo: Fiddle

Comments

0

jQuery.each

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.