• JavaScript高级 |如何玩转箭头函数?


    本文已收录于专栏
    ⭐️ 《JavaScript》⭐️

    箭头函数

    在ES6中新增了函数的简写方式----箭头函数,箭头函数的出现不仅简化了大量代码,也让代码看起来更加优雅,同时也解决了this指向问题,下面我们就来详细讲解如何玩转箭头函数。

    语法规则

    1. 之前的方法
    function foo1(){}
    var foo2 = function(name,age){
    	console.log("函数体代码"this,arguments);
      console.log(name,age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 箭头函数完整写法
    var foo3 = (name,age) => {
    	console.log("箭头函数的函数体")
      console.log(name,age);
    }
    
    • 1
    • 2
    • 3
    • 4
    1. 箭头函数遍历数组
    • 曾经的写法
    var names = ["abc","cba","nba"];
    
    names.forEach(function(item)){
    	console.log(item);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 箭头函数的写法
    names.forEach((item,idx,arr)=>{
      console.log(item,idx,arr);
    	} 
    )
    
    • 1
    • 2
    • 3
    • 4

    image.png

    setTimeout(()=>{
    	console.log("setTimeout");
    },3000)
    
    • 1
    • 2
    • 3

    简写规则

    1. 如果箭头函数只有一个函数,那么()可以省略
    name.forEach(item =>{
    console.log(item);
    }
    
    • 1
    • 2
    • 3
    • filter()配合箭头函数,可以高效的筛选出符合条件的数字。
    var newNums = nus.filter(item =>{
      return item % 2;
    })
    
    • 1
    • 2
    • 3
    1. 如果函数体中只有一行执行代码,那么{} 可以省略.
    • 并且这行代码的返回值会作为整个函数的返回值,所以不需要加 return
    names.forEach(item => console.log(item));
    
    • 1
    • filter()函数在只有一行执行,可以直接省略{}
    varans = worker.filter( item=>item % 2 )
    
    • 1
    1. 如果默认返回值是一个对象,那么这个对象必须加()

    注意:在react 的 redux 经常使用。
    我们会发现当箭头函数 同时遇到 执行体的大括号和对象的大括号时,箭头函数无法区分

    var arrFn = () =>{} //此大括号是执行体
    
    • 1
    var arrFn = () =>{ name : "why"}// 此大括号是对象
    
    • 1

    所以为了区别执行器,必须要给对象加()

    var arrFn = () =>({ name : "why"})
    
    • 1

    常见应用

    map

    map() 方法定义在JS的Array中,它返回一个新的数组,数组中的元素为原始数组调用函数后处理的值。
    值得注意的是:

    • map()函数不会对空数组进行检测。
    • map()函数不会改变原始数组,它形成的是一个新数组。
    • array.map(function(currentValue, index, arr), thisIndex)

    参数说明:

    • function(currentValue,index,arr):必填
      • 数组中的每个元素都会执行这个函数。
      • currentValue:必填,表示当前元素的值。
      • index:可选,当前元素的索引也就是第几个数组元素。
      • arr:可选,当前元素属于的数组对象。
    • thisValue:可选,对象作为该执行回调时使用,传递给函数,用作“this”的值。

    例1:对原数组进行平方后赋值给新数组。

    let arry = [1,2,3,4];
    let newArray = array.map((item)=>{
      return item*item;
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    也可以化简成下面一行代码。

    let newArray = array.map(item =>item * item)
    
    • 1

    例2:对原数组的偶数进行平方后赋值给新数组。

    filter

    filter() 用于对数组进行过滤。

    • 原理是它创建一个新数组,新数组的元素是通过检查指定数组中符合条件的所有元素。
    • filter把传入的函数依次作用在每一个元素,然后根据返回值是true还是false决定保留还是丢弃元素。
    • Array.filter(function(currentValue, indedx, arr), thisValue)

    参数说明:

    • function(currentValue,index,arr):必填
      • 数组中的每个元素都会执行这个函数。
      • currentValue:必填,表示当前元素的值。
      • index:可选,当前元素的索引也就是第几个数组元素。
      • arr:可选,当前元素属于的数组对象。
    • thisValue:可选,对象作为该执行回调时使用,传递给函数,用作“this”的值。
    let newArray = array.filter(item=>item%2===0).map(item =>item * item)
    
    • 1

    例3:对原数组中的偶数下标进行平方后赋值给新数组。

      let array = [1, 2, 3, 4];
      let newArray = array.filter((item,idx)=>idx%2===0).map(item =>item * item)
    
    • 1
    • 2

    例4:巧妙利用 arr 参数,给数组去重.

    var newArray = array.filter((item,idx,arr)=>arr.indexOf(item) === idx)
    
    • 1

    例2:对原数组的偶数进行平方后求累加和。

    reduce

    • 用于遍历数组,可以设置初始值,大大增强了代码的可读性,同时还有一个参数可以做累计计算。
    • array.reduce((pre, cur, index, arr),init)

    参数说明:

    • function((pre, cur, index, arr)):必填
      • pre: 必填,积累值
      • cur: 必填。当前元素。
      • index: 可选。当前下标。
      • arr: 可选。当前数组。
    • init: 可选。传递给函数的初始值,但传入参数为两个时,init 是累计值 pre的初始值。

    如果reduce的参数只有一个,那么累计值的初始值是数组的第一个值。

    如果reduce的参数有两个,那么积累值初始值就是设置好的 参数init初始值。

    在每一次迭代中,返回的值都作为下一次迭代的 pre累计值。

    var ans = arr.filter(item=>item%2).map(item=>item*item).reduce((x,y)=>x+y,0);
    
    • 1

    箭头函数中的this使用

    普通函数中是有this的标识符

    function foo(){
    	console.log("foo",this);
    }
    foo()//window
    foo.apply("aaa")//aaa
    
    • 1
    • 2
    • 3
    • 4
    • 5

    箭头函数中,压根没有this。

    var bar = ()=>{console.log("bar",this)}
    bar()//window
    bar.apply("AAA")//window
    
    • 1
    • 2
    • 3

    concat

    concat()方法是用于连接两个或多个数组。

    var arr  = [1, 2, 3, 4];
    var arr2 = [7, 8, 9, 10];
    var ans = [].concat(arr,arr2);
    
    console.log(ans);//输出:(8) [1, 2, 3, 4, 7, 8, 9, 10]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    this的查找规则

    因为箭头函数中没有this的标识符,所以当箭头函数内部开始调用this时。

    JavaScript引擎就从作用域由里到外的找含有this指向的作用域。

    var obj ={
    	name:"obj",
      foo:function(){
        var bar = ()=>{
          console.log("bar",this);
        }
        return bar;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 第一层 bar箭头函数:没有。
    • 第二层 function 函数:指向obj。

    所以例子中的 this 指向obj。

    var obj ={
    	name:"obj",
      foo:()=>{
      	var bar =()=>{
          console.log("bar:",this);
        }
        return bar;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 第一层 bar箭头函数:没有。
    • 第二层 foo箭头函数:没有。
    • 第三层 全局作用域:指向window。

    所以例子中的 this 指向window。

    模拟网络发送请求

    • 封装 request 工具函数
    function request(url,callback){
      	var res = ["abc","cba","nba"];
        callback(res);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 实际操作的位置
      • 早期的写法

    因为此时传入 request 的function ,就是 request 定义中的 callback()。
    所以 function 中的参数就是 request 定义中的 res 数组,然后赋值给了 此对象中names
    但因为 function 是个回调函数的this 的指向是 window,所以需要在外层的函数中,规定一个_this指向当前对象。

     var _this = this;
    
    • 1

    然后 将获取过来的 res 数组 赋值给 _this 中的names

      _this.name = [].concat(ans);
    
    • 1
    var obj = {
    	names:[],
      network:function(){
        var _this = this;
        request("/names",function(ans){
        _this.name = [].concat(ans);
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 箭头函数的写法

    因为箭头函数本身是没有 this的,js引擎会由内往外的找 this的指向。
    发现 外层的 函数 this指向obj,于是 this 就指向了 obj。

    var obj = {
    	names:[],
      network:function(){
        request("/names",(ans)=>{
        this.name = [].concat(ans);
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    完结散花

    ok以上就是对 JavaScript高级 |如何玩转箭头函数? 的全部讲解啦,很感谢你能看到这儿。如果有遗漏、错误或者有更加通俗易懂的讲解,欢迎小伙伴私信我,我后期再补充完善。

    参考文献

    coderwhy老师JS高级视频教程

  • 相关阅读:
    机器学习-Pytorch基础
    Tomcat部署(手动建立文件夹的形式)
    centos 部署java环境,拷贝jar包并运行
    【设计模式 05】原型模式
    R基础运算
    外卖机构怎么使用数字科技节省了工资支出
    莱特兄弟的家庭教育
    Vue学习笔记(二)
    【好书推荐】《Python编程:从入门到实践(第2版)》
    Python爬虫:原理与实战
  • 原文地址:https://blog.csdn.net/m0_66139206/article/details/126825538