Home  >  Article  >  Web Front-end  >  How to implement native map in js

How to implement native map in js

王林
王林forward
2020-03-26 10:12:302790browse

How to implement native map in js

JS native method map implementation, the code is as follows:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="author" content="杨欣">
  <title>map</title>
</head>

<body>

  <script>
    Array.prototype.my_map = function (callback) {
      if (!Array.isArray(this) || !this.length || typeof callback !== &#39;function&#39;) {
        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)
  </script>
</body>

</html>

(Recommended tutorial: js tutorial)

Supplementary knowledge points :

We usually use the encapsulated map method. If we encapsulate a map ourselves, how should we implement it.

The basic principle remains unchanged. In fact, the core of traversing an array is the for loop. Therefore, a map method is encapsulated below.

The ideas are as follows:

1. Add a method to the prototype

2. Pass a function and this

3. The parameters passed by the 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 i=0;i<arr.length;i++){
		let result = fn.call(context,arr[i],i,arr);
		temp.push(result);
	}
	return temp;
}

Recommended video tutorial: javascript video tutorial

The above is the detailed content of How to implement native map in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete