JavaScript advanced | how to play with arrow functions?

This article has been included in the column ⭐️ <JavaScript>⭐️

Arrow function

In ES6, an abbreviation of function - arrow function is added. The appearance of arrow function not only simplifies a lot of code, but also makes the code look more elegant. At the same time, it also solves the problem of this pointing. Next, we will explain how to play with arrow function in detail.

rule of grammar

  1. Previous methods
function foo1(){}
var foo2 = function(name,age){
	console.log("Function body code",this,arguments);
  console.log(name,age);
}
  1. Complete writing of arrow function
var foo3 = (name,age) => {
	console.log("Function body of arrow function")
  console.log(name,age);
}
  1. Arrow function traverses array
  • Once written
var names = ["abc","cba","nba"];

names.forEach(function(item)){
	console.log(item);
})
  • Writing method of arrow function
names.forEach((item,idx,arr)=>{
  console.log(item,idx,arr);
	} 
)

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

Abbreviation rules

  1. If the arrow function has only one function, the arrow function can be omitted
name.forEach(item =>{
console.log(item);
}
  • With the arrow function, filter () can efficiently filter out qualified numbers.
var newNums = nus.filter(item =>{
  return item % 2;
})
  1. If there is only one line of executable code in the function body, {} can be omitted
  • And the return value of this line of code will be the return value of the whole function, so there is no need to add return
names.forEach(item => console.log(item));
  • The filter() function is executed on only one line, and you can omit {}
varans = worker.filter( item=>item % 2 )
  1. If the default return value is an object, the object must be added with ()

Note: redux in react is often used.
We will find that when the arrow function encounters both the curly braces of the execution body and the curly braces of the object, the arrow function cannot distinguish

var arrFn = () =>{} //This brace is the executor
var arrFn = () =>{ name : "why"}// This brace is an object

So in order to distinguish the executors, we must add ()

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

Common applications

map

The map() method is defined in JS Array. It returns a new Array. The elements in the Array are the values processed after calling the function of the original Array.
It is worth noting that:

  • 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 is 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 number of array elements.
    • arr: optional array object to which the current element belongs.
  • thisValue: optional. The object is used when the callback is executed. It is passed to the function and used as the value of "this".

Example 1: assign a value to the new array after squaring the original array.

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

It can also be reduced to the following line of code.

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

Example 2: square the even number of the original array and assign it to the new array.

filter

filter() is used to filter the array.

  • The principle is that it creates a new array, and the elements of the new array are all qualified elements in the specified array.
  • The filter applies the incoming function to each element in turn, and then determines whether to keep or discard the element according to whether the return value is true or false.
  • Array.filter(function(currentValue, indedx, arr), thisValue)

Parameter Description:

  • function (currentValue, index, arr): required
    • This function is 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 number of array elements.
    • arr: optional array object to which the current element belongs.
  • thisValue: optional. The object is used when the callback is executed. It is 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: skillfully use the arr parameter to de duplicate the array

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

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

reduce

  • It is used to traverse the array, and can set the initial value, which greatly enhances the readability of the code. At the same time, there is a parameter that can be used for cumulative calculation.
  • array.reduce((pre, cur, index, arr),init)

Parameter Description:

  • function ((pre, cur, index, arr)): required
    • pre: required, accumulated value
    • cur: required. Current element.
    • index: optional. Current subscript.
    • arr: optional. Current array.
  • Init: optional. The initial value passed to the function, but when two parameters are passed in, init is the initial value of the cumulative value pre.

If there is only one parameter to reduce, the initial value of the cumulative value is the first value of the array.

If there are two parameters of reduce, the initial value of the accumulated value is the initial value of the set parameter init.

In each iteration, the returned value is taken as the pre cumulative value of the next iteration.

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

Use this in arrow function

In a normal function, there is an identifier of this

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

In the arrow function, there is no this at all.

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

concat

The concat() method is used to connect two or more arrays.

var arr  = [1, 2, 3, 4];
var arr2 = [7, 8, 9, 10];
var ans = [].concat(arr,arr2);

console.log(ans);//Output: (8) [1, 2, 3, 4, 7, 8, 9, 10]

Search rules for this

Because there is no identifier of this in the arrow function, when this is called inside the arrow function.

The JavaScript engine looks for the scope pointed to by this from the inside out of the scope.

var obj ={
	name:"obj",
  foo:function(){
    var bar = ()=>{
      console.log("bar",this);
    }
    return bar;
  }
}
  • First level bar arrow function: No.
  • The second level function function: points to obj.

So this in this example points to obj.

var obj ={
	name:"obj",
  foo:()=>{
  	var bar =()=>{
      console.log("bar:",this);
    }
    return bar;
  }
}
  • First level bar arrow function: No.
  • The second layer is foo arrow function: No.
  • Level 3 global scope: point to window.

So this in this example points to window.

Simulate network sending request

  • Encapsulate the request tool function
function request(url,callback){
  	var res = ["abc","cba","nba"];
    callback(res);
}
  • Actual operation location
    • Early writing

Because the function passed in to the request at this time is callback () in the request definition.
Therefore, the parameter in the function is the res array in the request definition, and then assigned to the names in this object
However, since function is a callback function and this points to window, it is necessary to specify a_ This points to the current object.

 var _this = this;

Then assign the obtained res array to_ names in this

  _this.name = [].concat(ans);
var obj = {
	names:[],
  network:function(){
    var _this = this;
    request("/names",function(ans){
    _this.name = [].concat(ans);
  })
}
  • Writing method of arrow function

Because the arrow function itself does not have this, the js engine will look for the point of this from the inside out.
It is found that the outer function this points to obj, so this points to obj.

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

End scattered flowers

ok the above is the advanced JavaScript | how to play with arrow functions? Thank you very much for seeing it here. If there are omissions, errors or more easy to understand explanations, you are welcome to write me a private letter, and I will supplement and improve it later.

reference

coderwhy teacher JS advanced video tutorial

Tags: Front-end Javascript React

Posted by dragonfly4 on Tue, 13 Sep 2022 02:25:56 +0930