扩展运算符(...)+map配合,给数组的每个元素加内容、map说明(ES5)

<!DOCTYPE html>
<html lang="en">
<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">
    <title>扩展运算符练习</title>
</head>
<body>
    <script>
        /*
        现在在classGrade数组里面给每个值后面都加个班字
        */
        const classGrade=['1313','1611'];
        function addWord(word){
            return [...word].map(letter=>`${letter}班`)
        }
        console.log(addWord(classGrade));//(2) ["1313班", "1611班"]
    </script>
</body>
</html>

map说明(ES5):
     起到一个映射的作用;
        返回一个新的数组;
        有两个参数:
          第一个参数是:callback回调函数
            callback回调函数里面的第一个参数是:
                 ele代表着正在处理的元素
            callback回调函数里面的第二个参数是:
                 index代表着数组的索引值
            callback回调函数里面的第三个参数是:
                 self代表着数组本身
          第二个参数是:thisArg(可选)
                代表着this默认指向window

const arr = [
    { name: '张三', age: 21 },
    { name: '李四', age: 22 },
    { name: '王五', age: 23 },
  ];
  let obj = {naem: 'xyz'}
  const newMap = arr.map(function(ele, index, self){
    console.log(this)
    return ele.age + 10
  }, obj)
  console.log(newMap)

result:


通过源码实现map方法:

//通过源码实现map方法
  const arr = [
    { name: '张三', age: 21 },
    { name: '李四', age: 22 },
    { name: '王五', age: 23 },
  ];
  Array.prototype.myMap = function (func) {
    let arr = [];
    let _this = arguments[1] || window;
    for (let i = 0; i < this.length; i++) {
      arr.push(func.apply(_this, [this[i], i, this]))
      // arr.push(func.call(_this, this[i], i, this)
    }
    return arr
  }
  let obj = {
    naem: 'xyz'
  }
  let newMap = arr.myMap(function (ele, index, self) {
    console.log(this)
    return ele.age + 21
  })
  console.log(newMap)

result:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值