Array.eq () vs. array [] in javascript and jquery

When accessing an array, when is it advisable to use the .eq () function?

For example, I have ...

slides.eq(slidesLength-1).css("z-index", (slidesLength-1)); 

and later I ...

 for(i=0; i<slidesLength-1; i++) { $(slides[i]).css("left", "-100%"); } 

In the first code snippet, the slide show stops functioning if I do not use the .eq () function. However, the second part seems to work whether I use the .eq () function or not. Why is this?

+6
source share
3 answers

slides not an array. This is a jQuery object. The .eq() method returns you the element at the specified index as a jQuery object.

Although jQuery objects may not be arrays, they may pretend to have a length property, as well as properties corresponding to indexes. (Since they are not arrays, you cannot name methods like .pop() , .forEach() , etc.)

When you execute slides[i] , you are actually getting a DOM element, not a jQuery object. The $() function turns a DOM element into a jQuery object.

So, when you do slides.eq(1) , internally jQuery does $(slides[i]) .

PS Objects, such as jQuery objects that pretend to be arrays, are called "array-like objects." If you are console.log(slides) , it may look like an array. This is just your console, trying to make things convenient for you. (See This Question for more information: Creating Objects Like Arrays in JavaScript )

+6
source

.eq() is a jQuery method that returns a jQuery object, while accessing by index returns a simple DOM element. You should use eq() when you want to use jQuery ( css() methods in this case) for the returned selection.

The reason $(slides[i]) is because you are creating a jQuery object by passing a simple element to the $() constructor.

+5
source

Your slides variable is not an Array , but a jQuery object.

.eq() returns a jQuery object, ultimately empty if index is outside the bounds and a negative index counted from the end.

.get() returns a DOM element or undefined if index is outside the bounds and a negative index is counted from the end.

[] returns a DOM element or throws an error if index goes out of bounds.

...

In addition, jQuery methods allow you to interact with a set of elements, as it was alone. So if you do this:

 slides.css("left", "-100%"); 

It applies to every matched element contained in a jQuery object. There is no need to sort them out.

...

Also the preferred way to loop over matched elements is each() method:

 slides.each(function (i, el) { var $el = $(el); }); 

...

A standard convention with a jQuery variable prefix with the $ sign is also set; it makes it easy to distinguish DOM elements from jQuery objects. But this is only a matter of taste.

+3
source

All Articles