js如何实现原生map


本文摘自PHP中文网,作者V,侵删。

js原生方法map实现,代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<!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 !== '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)

  </script>

</body>

 

</html>

(推荐教程:js教程)

补充知识点:

我们平时用的是已经封装好的map方法,如果让我们自己封装一个map,应该如何实现。

万变不离其宗,其实遍历数组的核心还是for循环。因此下面封装一个map方法。

思路如下:

1、在原型上添加一个方法

2、传一个函数和this

3、call 方法传的参数和封装好的map方法的参数是一样的。

1

2

3

4

5

6

7

8

9

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;

}

推荐视频教程:javascript视频教程

以上就是js如何实现原生map的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

js实现图片无缝滚动

js读写cookie

在html中嵌入js代码的方法

js如何实现多图与单图的上传显示

js实现改变html上文字颜色和内容的方法

详细介绍下js中的window与document

js如何实现日期比较大小

js变量的基本使用方法介绍

js中相等判断===、==、object.is()的区别

jquery怎么写ajax

更多相关阅读请进入《js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...