Member-only story

JavaScript Interview Questions

Refer to Array.prototype.map, How to Implement the map method of the Object version?

Shuai Li
Sep 20, 2021

Question

We know that the array instance has a map method that creates a new array populated with the results of calling a provided function on every element in the calling array:

Now we want to add a map method to the prototype of the object to achieve this effect:

What should we do?

This is a code template:

Object.prototype.map = function(callbackFn){
// your code
}

Answer

In fact, the idea of this question is very simple. In the map method, we only need to traverse all the properties of the object, then execute the callback function, and finally store the result of the callback function.

Here is the implementation:

--

--

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.

No responses yet