0

I have array. I have to run loop after indexing 1. I google it but did not find any answer so I did it by use of for loop. Is there any way to get this done by using of jquery without any extra effort . Like using slice and all that.

var myAr= ['a','b','c','d']
for(i=2;i<myAr.length;i++){
alert(myAr[i])
}


$.each(myAr,function(){
// what goes here
})
1
  • Both answers below are correct — see $.each documentation for more info. Commented May 8, 2015 at 18:34

4 Answers 4

1
$.each(myAr,function(index){
    if(index < 2) {
        return;
    }
    // your code
})
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't it be if (index < 2)?
Yes it should.Thanks.
But I see no difference from the first answer.
1

You could slice the array first:

$.each(myAr.slice(2), function(i, val) {
    ...
});

Inside the function, the indexes will be 2 less than they would be if you were processing the original array.

Performance-wise, the for loop is probably best. It only processes the desired elements of the array, and it doesn't perform any function calls.

Next are the answers that test the index within the loop.

My solution is probably worst, because it has to make 2 passes through the array: once to make the slice, and then to perform the $.each loop over the slice. It also uses more memory, because the slice is a new array.

2 Comments

Ok as I mention in my question. Is there any way without using slice. But I think performance wise this answer is better
Actually, this is probably the worst performance. I added an explanation of why.
0

https://api.jquery.com/jquery.each/

I am pretty sure that pure javascript is faster than the JQuery one, but it is a convenient function :

$.each(myAr,function(index, value){
    if(index > 1) {
        alert(key + ": " + value)
    }    
})

2 Comments

But loop is running through out the array. I want to avoid that.
@amit Then use the for loop, what's the problem with that?
0

$( "div" ).each( function( i ){
  if( i == 0 ) return; 
  console.log( this );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div> </div>
<div> </div>

1 Comment

Should be if (i < 2)

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.