What is the method of js native map implementation
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