How to use arrow functions in JavaScript
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.
[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); } )
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.
-
filter
Apply the passed function to each element in turn, and then decide whether to keep or discard the element based on whether the return value istrue
orfalse
. 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
