Arrays.map
The Array.prototype.map method creates a new array populated with the results of calling a provided function on every element in the calling array.
code
Array.prototype.myMap = function (callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
arr.push(callbackFn(this[i], i, this));
}
return arr;
};
Explanation:
- Initialization:
- var
arr = [];initializes a new empty array to store the results.
- Loop through the array:
for (var i = 0; i < this.length; i++) { ... }loops through each element of the array.
- Callback Execution:
callbackFn(this[i], i, this)calls the provided function callbackFn with three arguments: -this[i]:the current element.i:the index of the current element. this: the array being processed.
- Push Results:
arr.push(callbackFn(this[i], i, this));stores the result of callbackFn in the new array.
- Return New Array:
- return
arr;returns the new array with the transformed elements.