Home > Web Front-end > JS Tutorial > body text

How to implement native map in js

王林
Release: 2020-03-26 10:12:30
forward
2865 people have browsed it

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>
Copy after login

(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;
}
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template