javascript实现数组的map方法

13 阅读1分钟
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    //数组的map方法:返回按回调函数处理好的数组
    arr = [1,2,3]
    const arrRes = arr.map(item => item *2)
    console.log(arrRes);
    
    //接收一个回调函数,遍历元素,返回回调函数里面返回的元素处理结果拼接成的数组里面
    //挂载到Array的原型对象上,数组能够访问到
    Array.prototype.myMap = function(fn){
      if(typeof fn !== "function"){//如果不是函数就打印错误
        console.log("Object is not a function");
      }
      //定义一个空数组,不改变原数组
      let arrRes = []
      //遍历元素
      for(let i=0;i<this.length;i++){
        arrRes.push(fn(this[i]))//将回调函数的返回值添加在数组里面
      }
      //返回处理后的数组
      return arrRes
    }
    const arrRes2 = arr.myMap(item => item *8)
    console.log(arrRes2);
    
  </script>
</body>
</html>