In my spare time I work on a private website. My self-teaching is really unstructured, and I've run up against a huge hole in my fundamentals.
I'm looking at a jQuery example from the jQuery API website, serializeArray, and I can't wrap my head around the ShowValues function.
Here's how it goes:
function showValues() {
var fields = $(":input").serializeArray();
$("#results").empty();
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
});
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
And I'm pretty sure I get what's going on in everything except lines 4 and 5:
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
jQuery goes through each key in the fields array and puts what it finds through the generic function: function(i,field)
that function uses its two parameters to produce a string to append to #results.
My questions:
Why does that function need two parameters? The variable i seems to count up from zero, for each time the function is run. and if it's taken out of the function, field.value returns undefined.
Since the values coming in to the two-parameter function are arranged into an array, the function has to...match the dimensions of the array?
Is i
special, or could any spare variable be used?
And what's happening with field.value
? .value
isn't in the jQuery API, but I think it's still plucking values from the second position in the fields array?
Why does the function need two parameters?
First of all you should read the documentation of .each. It tells you that it expects a function defined as such:
callback(indexInArray, valueOfElement)
That has been decided, so you have to abide to it (the reasoning is beyond this answer).
If you define your callback as such
function(indexInArray, valueOfElement, foo) { ... }
and it is called as
callback(indexInArray, valueOfElement)
then foo
will be undefined.
If you define your callback as
function(foo) { ... }
it will still be called as
callback(indexInArray, valueOfElement)
and foo
will contain the indexInArray
- and 0.value
will of course be undefined if you "leave out the i
".
Can I use a spare variable?
Yes you can. In most functional languages you will find _
used for parameter that you don't care about (be careful if you use libraries like underscore.js
though). Any other name can be used.
$(...).each(function(_, elem) {
...
});