Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.eq() vs. array[] in Javascript and Jquery

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

For example, I have...

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

and later I have...

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

In the first piece of code, the slideshow stops functioning if I don's use the .eq() function. However, the second piece seems to function whether I use the .eq() function or not. Why is this?

like image 735
Ivan Potosky Avatar asked Dec 22 '15 15:12

Ivan Potosky


People also ask

What is the difference between EQ () and get () methods in jQuery?

eq() returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions. . get() returns an array of raw DOM elements. You may manipulate each of them by accessing its attributes and invoking its functions as you would on a raw DOM element.

What does Eq do in jQuery?

jQuery :eq() Selector The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

What is array () in JavaScript?

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements".


2 Answers

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

While jQuery objects may not be arrays, they can pretend to be by having a length property as well as properties corresponding to the indexes. (Since they are not arrays, you can't call methods like .pop(), .forEach(), etc. on them.)

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

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

P.S. Objects, like jQuery objects, that pretend to be arrays are called "array-like objects". If you 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 info: Creating array-like objects in JavaScript)

like image 120
Rocket Hazmat Avatar answered Sep 29 '22 19:09

Rocket Hazmat


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

The reason $(slides[i]) works is because you're constructing a jQuery object by passing the plain element to $() constructor.

like image 37
T J Avatar answered Sep 29 '22 19:09

T J