Home  >  Article  >  Web Front-end  >  How to use arrow functions in JavaScript

How to use arrow functions in JavaScript

WBOY
WBOYforward
2022-10-02 08:00:281327browse

This article brings you relevant knowledge about JavaScript video tutorial, which mainly introduces related issues about arrow functions, including grammar rules, abbreviation rules, common applications, etc., Let’s take a look at it together, I hope it will be helpful to everyone.

How to use arrow functions in JavaScript

[Related recommendations: JavaScript video tutorial, web front-end

Arrow function

In ES6, a new abbreviation method for functions - arrow function is added. The emergence of arrow function not only simplifies a lot of code, but also makes the code look more elegant. It also solves the problem of this pointing. Let's go into details below. Explain how to play with arrow functions.

Grammar rules

  • Previous method

function foo1(){}var foo2 = function(name,age){
	console.log("函数体代码",this,arguments);
  console.log(name,age);}
  • Complete writing method of arrow function

var foo3 = (name,age) => {
	console.log("箭头函数的函数体")
  console.log(name,age);}
  • Arrow function traverses the array

  • Once How to write
var names = ["abc","cba","nba"];names.forEach(function(item)){
	console.log(item);})
  • How to write arrow function
names.forEach((item,idx,arr)=>{
  console.log(item,idx,arr);
	} )

How to use arrow functions in JavaScript

setTimeout(()=>{
	console.log("setTimeout");},3000)

Abbreviation rules

  • If the arrow function has only one function, then () can be omitted

name.forEach(item =>{console.log(item);}
  • filter () combined with the arrow function can efficiently filter out numbers that meet the conditions.
var newNums = nus.filter(item =>{
  return item % 2;})
  • If there is only one line of execution code in the function body, then {} can be omitted.

  • And The return value of this line of code will be used as the return value of the entire function, so there is no need to add return
names.forEach(item => console.log(item));
  • filter() function is executed in only one line, you can directly omit {}
varans = worker.filter( item=>item % 2 )
  • If the default return value is an object, then this object must be added ()

Note: Often used in react's redux.
We will find that when the arrow function encounters the braces of the executor and the braces of the object at the same time, the arrow function cannot distinguish

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

So in order to distinguish the executor, you must add () to the object

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

Common Applications

map

The map() method is defined in JS’s Array. It returns a new array, and the elements in the array are the original array calling functions. post-processing value.
It is worth noting:

  • The map() function does not detect empty arrays.
  • The map() function does not change the original array, it forms a new array.
  • array.map(function(currentValue, index, arr), thisIndex)

Parameter description:

  • function( currentValue, index, arr): required
    • This function will be executed for each element in the array.
    • currentValue: required, indicating the value of the current element.
    • index: Optional, the index of the current element is the array element.
    • arr: Optional, the array object to which the current element belongs.
  • thisValue: Optional, the object is used as the execution callback, passed to the function, and used as the value of "this".

Example 1: Square the original array and assign it to the new array.

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

can also be simplified to the following line of code.

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

Example 2: Square the even numbers of the original array and assign them to the new array.

filter

filter() is used to filter arrays.

  • The principle is that it creates a new array, and the elements of the new array are checked by checking all elements in the specified array that meet the conditions.
  • filterApply the passed function to each element in turn, and then decide whether to keep or discard the element based on whether the return value is true or false .
  • Array.filter(function(currentValue, indedx, arr), thisValue)

Parameter description:

  • function( currentValue, index, arr): required
    • This function will be executed for each element in the array.
    • currentValue: required, indicating the value of the current element.
    • index: Optional, the index of the current element is the array element.
    • arr: Optional, the array object to which the current element belongs.
  • thisValue: Optional, the object is used as the execution callback, passed to the function, and used as the value of "this".
let newArray = array.filter(item=>item%2===0).map(item =>item * item)

Example 3: Square the even subscripts in the original array and assign them to the new array.

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

Example 4: Cleverly use the arr parameter to deduplicate the array.

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

Example 2: Find the cumulative sum after squaring the even numbers of the original array.

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);

箭头函数中的this使用

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

function foo(){
	console.log("foo",this);}foo()//windowfoo.apply("aaa")//aaa

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

var bar = ()=>{console.log("bar",this)}bar()//windowbar.apply("AAA")//window

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]

this的查找规则

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

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

var obj ={
	name:"obj",
  foo:function(){
    var bar = ()=>{
      console.log("bar",this);
    }
    return bar;
  }}
  • 第一层 bar箭头函数:没有。
  • 第二层 function 函数:指向obj。

所以例子中的 this 指向obj。

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

所以例子中的 this 指向window。

模拟网络发送请求

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

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

 var _this = this;

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

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

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

var obj = {
	names:[],
  network:function(){
    request("/names",(ans)=>{
    this.name = [].concat(ans);
  })}

【相关推荐:javascript视频教程web前端

The above is the detailed content of How to use arrow functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete