在Javascript和Jquery中的array.eq()与array [] [英] array.eq() vs. array[] in Javascript and Jquery
问题描述
访问数组时,何时使用.eq()函数?
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%");
}
在第一段代码中,如果我不使用幻灯片,则幻灯片停止运行.eq()函数。但是,无论我是否使用.eq()函数,第二部分似乎都起作用。这是为什么?
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?
推荐答案
幻灯片
不一个数组。这是一个jQuery对象。 .eq()
方法返回给您指定索引处的元素作为 jQuery对象。
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.
虽然jQuery对象可能不是数组,但它们可以假装具有 length
属性以及与索引对应的属性。 (因为它们不是数组,所以不能调用 .pop()
, .forEach()
等方法,等等。)
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.)
当您执行 slides [i]
时,您实际上正在获取 DOM元素,而不是jQuery对象。 $()
函数将DOM元素转换为jQuery对象。
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.
因此,当你执行<$ c时$ c> slides.eq(1),内部jQuery正在执行 $(slides [i])
。
So, when you do slides.eq(1)
, internally jQuery is doing $(slides[i])
.
PS像jQuery对象一样假装成数组的对象称为类数组对象。如果您 console.log(幻灯片)
,它可能看起来像一个数组。这只是您的控制台,试图让您方便。 (有关详细信息,请参阅此问题:在JavaScript中创建类似于数组的对象)
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)
这篇关于在Javascript和Jquery中的array.eq()与array []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!