开发者

Is jQuery an Array?

I'm just getting into jQuery and I am having problems understanding what it is. How can I use array style indexing on a jQuery object but 开发者_Python百科jQuery not be an array? Is this a javascript thing?

<ul id="myUL">
<li></li>
<li id="second"></li>
<li></li>
</ul>

var jqueryObject = $("#myUL > li");
alert(jqueryObject[1].attributes.getNamedItem("id").value);

if (jqueryObject instanceof Array) {
    alert('value is Array!');
} else {
    alert('Not an array');//this is what pops up
}


A jQuery collection is an Object with properties numbered like Array indexes (and some other properties and methods), each holding one of the matched elements. It is also given a length property to tell you how many elements the selector matched. See http://api.jquery.com/Types/#jQuery

Also, yes, it is partly a JavaScript thing--JS lets you access an object's properties with dot notation or with square-bracket notation.


Per docs, no:

The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().


jQuery collection wrapper is an Object in JS sence.

JS objects have operator[] that in general can accept any type as an index. So these statements are valid:

var obj = {};
obj[0] = element1;
obj[1] = element2;
//...
obj[10] = element10;
// and yet
obj[false] = someValue1;
obj[true] = someValue2;
// and obviously 
obj["first"] = 1; // equivalent (but not exact) of obj.first = 1;
obj["second"] = 2; 

In short object is a key/value map where key can be of any type.


It isn't. But if you wanna use JS Array methods, like .join() after a $(...).map(...) call, you can use the $.makeArray that converts a jQuery collection to a true JS Array:

http://api.jquery.com/jQuery.makeArray/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜