How a function callback works
I have the following code
$.map( [ 0, 1, 2 ], function( n ) {
return n > 0 ? n + 1 : null;
});
Out Put: [2, 3]
I know $.map
Translate all items in an array or object to new array of items.
( Documentation ).
What I want to know how call back function
to .map
work (internal implants)?
One possible answer might be
-
.map
has some loop that passes each element of the array intocall back method
, which returns some value. -
.map
manages every return value fromcall back method
. In this case, push into some internal array. .map
Return an array at the end of the loop .
EDIT
But I'm not sure how it works, does it work as I explained?
+3
source to share
2 answers
But I'm not sure how it works?
Yes, that's basically how it works. Complete information, as always, in the source code (line number will rot over time ...). It currently looks like this:
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
+2
source to share
Well, there is no better way to test than by looking at the source code
function (elems, callback, arg) {
var value, i = 0,
length = elems.length,
isArray = isArraylike(elems),
ret = [];
// Go through the array, translating each of the items to their new values
if (isArray) {
for (; i < length; i++) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
// Go through every key on the object,
} else {
for (i in elems) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
}
// Flatten any nested arrays
return concat.apply([], ret);
}
- Yes, be it version or object
Array
, it is a loop and a callcallback
to set the value - Yes, for both loops the value is pressed
- Yes, it returns a flattened array by calling
concat
+2
source to share