I have come across the following jQuery code but could not understand it. What does the following code, specially the "$([])" part in the last line mean ?
var instrument = $("#instrument"),
quantity = $("#quantity"),
orderType = $("#orderType"),
price = $("#price"),
validityDate = $("#validityDate"),
allFields = $([]).add(instrument).add(quantity).add(orderType).add(price).add(validityDate)
Looks like it's defining an array, then add()ing the DOM elements to it. From the manual:
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
[]
is an empty javascript array. As frunsi notes, this is not correct usage, and the []
definition is not required to create an empty set of elements, in 1.4 $()
will do ths for you.
It creates an empty jQuery set. This kind of usage is wrong, though it may work. The []
is superfluous.
Correct would be just $()
.
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.
http://api.jquery.com/jQuery/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With