开发者

What does $([]) mean in jQuery?

var username = $("#username"),
                password = $("#password"),
                allFields = $([]).add(username).add(password);

What is allFields? What is $([])?

Being a newbie to Javascript/jQuery, I've never seen 开发者_开发知识库this $([]) notation before and I'm interested in its associated methods.

Given that its "$([])", it's tricky to search for. And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing.

So what is $([])? Can anyone point me to some documentation? I'm interested in learning how to use this strange thing.


The jQuery function accepts an array of DOM nodes.

$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array.

Calling the jQuery function without any arguments returns an empty set. Taken from jQuery docs,

Returning an Empty Set

As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.

So, your example would work the same if you had instead called

$().add(username).add(password);

As other answers have mentioned and the docs say, passing an empty array was required before v 1.4.


[] it's an empty array. Wrapping it with $() overcharges it with jQuery's functions.

In javascript you can create an array this way:

var foo = [];


It is an empty array being passed in the creation of a jQuery object. Presumably to initialize something.

Shouldn't be necessary, at least not in the latest versions of jQuery.

Here's an example without the Array: http://jsfiddle.net/MAzLN/

Works fine, as the alert() shows one element in the object.

jQuery initializes the length property to 0 when the object is created, so I'm not sure what the purpose is, unless it was required in the past.


I believe it creates an empty jQuery collection object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜