Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery eq() caused infinite iteration

When I try to sum things up in my code, I figured out when I write something like this:

var $elements = $('div');
for ( var i = 0, $element; $element = $elements.eq(i); i++ ) {
    $element.text( 'Hello' );
}

the loop will never end. I would like to know, why that is happening. Caused it an error if I call functions inside condition or does jQuery just not return accurate data so therefore the loop-condition can't recognize the current index?

like image 224
kindisch Avatar asked Oct 25 '25 12:10

kindisch


1 Answers

The .eq() method always returns a jQuery object. If you specify an index that doesn't exist you get an empty jQuery object. But any object is truthy, so your loop condition is always truthy even after i goes past the last element. So, infinite loop.

You need to test the length:

for ( var i = 0, $element; i < $elements.length && ($element = $elements.eq(i)) ; i++ )

But why not just use the .each() method to loop?

The pattern of assigning the current element as the loop condition does work with an array:

for ( var i = 0, element; element = anArray[i]; i++ ) 

assuming none of the elements have a falsey value, because when i reaches an array.length then anArray[i] will be undefined which is falsey.

like image 67
nnnnnn Avatar answered Oct 28 '25 02:10

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!