Is n
automatically set to represent array indexes starting from 0? What confuses me is that I usually set up for loops to define i
as an index indicator. But here how does n
do it without being set that way?
x is an array
function maps(x){
return x.map(
function (n) {
return n*2
}
)
}
I was trying to double each element of an array. And i actually figured it out but my question is "how does it actually work?".
The function (n) { return n*2 }
is accepted as an argument of a callback function by the map() method. So function (n) { return n*2 }
executes for each element in the array x and its return value is added as a single element in the new array. The parameter n represents the current element being processed in the array and the second parameter should be the index of the current element being processed in the array. For example, we can turn your code snippet as the following:
let arr = [30, 51, 76];
function maps(x){
return x.map( function (n, index) {
console.log(n + " " + index);
return n*2;
} )
}
console.log(maps(arr));
Then we should get the result:
30 0
51 1
76 2
[ 60, 102, 152 ]
And we can see the indices that correspond to the elements.
I think the best way to eliminate your confusion is to figure it out how the map() method is defined. Here, I cite a piece of code snippet from https://jsvault.com/array-map to show what exactly is a map() method:
/**
* The callback gets 3 arguments
* the item, the index and the execution context
*/
Array.prototype.newMap = function (callback) {
const result = [];
for (let index = 0; index < this.length; index++) {
// This is primarily to check if the item
// exists in the array,
if (this.indexOf(this[index]) > -1) {
result[index] = callback(this[index], index, this)
}
}
return result
}
Within the definition, there is a for loop to handle a callback function, in which case, it could be your function (n) { return n*2 }
.
If you want to know more details, please check the links https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
and
https://jsvault.com/array-map