简体   繁体   中英

why are square brackets used in javascript function calls? jquery

From: andrew whittakers example showing result numbers in a custom jquery autocomplete implementation

 _response: function(contents){
        $.ui.autocomplete.prototype._response.apply(this, arguments);
        $(this.element).trigger("autocompletesearchcomplete", [contents]);
    }

why [contents] and not contents ?

It's a requirement from jQuery 's trigger function that the second parameter be an array (prior to 1.6.2), thus the wrapping to make it an array. From the trigger docs (emphasize by me):

$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a .trigger() call, these parameters will be passed along to the handler as well. To pass more than one parameter, use an array as shown here. As of jQuery 1.6.2, a single parameter can be passed without using an array.

So as of 1.6.2, it's actually not necessary to wrap the single argument in an array.

If the function expects an array, then you put your one or more elements in square brackets. For example, trigger 's function declaration is

.trigger( eventType [, extraParameters] )

Since you may want to give it more than one extra parameters, it accepts an array of them. If you have only one extra parameter to give, such as "contents" in your case, then you can put it into an array (or if you have just one parameter, you also can not put it into an array, as JQuery now accepts either way).

As Trinh pointed out its an array [content] with one element.

I dont know why but if you change it to content instead of [content] it will search for the query in the whole word.

If its [content] it will search only at the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM