This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
151. implement Array.prototype.map()
One possible implementation of Array.prototype.map()
can be as follows:
Array.prototype.myMap = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { result.push(callback(this[i], i, this)); } return result;};// example usage[1, 2, 3].myMap(num => num * 2); // [2, 4, 6]
This implementation creates a new empty array (result
) and iterates through each element of the calling array using a for
loop. At each iteration, the callback
function is called with three arguments: the current element, the index of the current element, and the calling array itself. The value returned by the callback
function is then added to the result
array using the push()
method. Finally, the result
array is returned.