Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the method of js native map implementation

Shulou Source: shulou.com Published: 2022-06-02 06:47:48 09月23日 Update

Today, I will talk to you about the method of js native map implementation, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Implementation of js Native method map

Map

Array.prototype.my_map = function (callback) {

If (! Array.isArray (this) | |! this.length | | typeof callback! = = 'function') {

Return []}

Else {let result = []

For (let index = 0

Index

< this.length; index++) { const element = this[index]; result.push(callback(element, index, this)) } return result } } let arr = [1, 2, 3, 4, 5] let res = arr.my_map((ele, i) =>

{

Return ele + 10})

Console.log (res)

Supplementary knowledge points

We usually use the encapsulated map method, if we let us encapsulate a map, how to implement it.

Everything remains the same, but the core of the traversal array is the for loop. So the following encapsulates a map method.

Train of thought:

1. Add a method to the prototype 2. The parameters passed by a function and the this3.call method are the same as those of the encapsulated map method.

Array.prototype.fakeMap = function (fn,context) {let arr = this;let temp = []; for (let itemositani

Tags: Methods encapsulation content parameters knowledge all the same functions prototypes ideas arrays more core knowledge points articles industry information information channels or channels into one Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Information Redmi Apple Shulou Tech Info