Be the first to experience new features of JavaScript ES12
The
JavaScript column introduces how to experience the new features of ES12.
Every year, JavaScript will be updated to add new features and new standards. ES2020 was released this year, and ES2020 (ES12) is also expected to be released next year, that is, 2021. Released mid-year. New features every year go through four stages, and the fourth stage is the last stage. What this article will introduce is the relevant new features in Proposal 4, which also means that these new features will appear in the next version to a large extent.
Feature preview:
- String.prototype.replaceAll New replaceAll
- Promise.any
- WeakRefs
- Logical operators and assignment expressions
- Number delimiters
replaceAll
It is easy to think of the word replaceAll to replace. In JavaScript, the replace method can only replace the first instance character matched in the string, but cannot perform global multiple matching replacement. The only way is to perform relevant rule matching and replacement through regular expressions
replaceAll returns a new string, and all characters that match the matching rules will be replaced. The replacement rules can be strings or regular expressions.
let string = 'I like 前端,I like 前端公虾米'//使用replacelet replaceStr = string.replace('like','love')console.log(replaceStr) // 'I love 前端,I like 前端公虾米'//replace使用正则匹配所有console.log(string.replace(/like/g,'love')) // 'I love 前端,I love 前端公虾米'//使用replaceAlllet replaceAllStr = string.replaceAll('like','love')console.log(replaceAllStr) // 'I love 前端,I love 前端公虾米'复制代码
It should be noted that when replaceAll uses regular expressions, if it does not match globally (/g), replaceAll() will throw an exception
let string = 'I like 前端,I like 前端公虾米'console.log(string.replaceAll(/like/,'love')) //TypeError复制代码
Promise.any
When any promise in the Promise list is successfully resolved, returns the result status of the first resolve If all promises are reject, an exception is thrown indicating that all requests failed
Promise.any([ new Promise((resolve, reject) => setTimeout(reject, 500, '哎呀,我被拒绝了')), new Promise((resolve, reject) => setTimeout(resolve, 1000, '哎呀,她接受我了')), new Promise((resolve, reject) => setTimeout(resolve, 2000, '哎呀,她也接受我了')), ]) .then(value => console.log(`输出结果: ${value}`)) .catch (err => console.log(err))//输出//输出结果:哎呀,她接受我了复制代码
Let’s look at another situation
Promise.any([ Promise.reject('Error 1'), Promise.reject('Error 2'), Promise.reject('Error 3') ]) .then(value => console.log(`请求结果: ${value}`)) .catch (err => console.log(err))//输出AggregateError: All promises were rejected复制代码
Promise.any and Promise.race are very easy to confuse. Be sure to distinguish between them. Once a promise triggers resolve or reject, Promise.race directly returns the status result and Don't care about its success or failure
WeakRefs
Use the Class class of WeakRefs to create a weak reference to the object (a weak reference to the object means that the object will not be recycled when it should be recycled by GC) Prevent GC's recycling behavior)
When we create a variable through (const, let, var), the garbage collector GC will never delete the variable from memory as long as its reference remains Existence is accessible. WeakRef objects contain weak references to objects. A weak reference to an object does not prevent the GC from restoring a reference to the object; the GC can delete it at any time.
WeakRefs are useful in many situations, such as using Map objects to implement key-value caches that require a large amount of memory. In this case, the most convenient thing is to release the memory occupied by the key-value pairs as soon as possible.
Currently, you can use WeakMap() or WeakSet() to use WeakRefs
Give a chestnut
I want to track the number of times a specific object calls a specific method. If it exceeds 1,000, a corresponding prompt will be made.
let map = new Map()function doSomething(obj){ ... }function useObject(obj){ doSomething(obj) let called = map.get(obj) || 0 called ++ if(called>1000){ console.log('当前调用次数已经超过1000次了,over') } map.set(obj, called) }复制代码
Although the above can achieve our function, a memory overflow will occur because it is passed to doSomething Each object of the function is permanently stored in the map and will not be recycled by GC, so we can use WeakMap
let wmap = new WeakMap()function doSomething(obj){ ... }function useObject(obj){ doSomething(obj) let called = wmap.get(obj) || 0 called ++ if(called>1000){ console.log('当前调用次数已经超过1000次了,over') } wmap.set(obj, called) }复制代码
Because it is a weak reference, the key-value pairs of WeakMap and WeakSet are Non-enumerable
WeakSet is similar to WeakMap, but each object in WeakSet may only appear once, and all objects in WeakSet are unique
let ws = new WeakSet()let foo = {}let bar = {} ws.add(foo) ws.add(bar) ws.has(foo) //truews.has(bar) //truews.delete(foo) //删除foo对象ws.has(foo) //false 已删除ws.has(bar) //仍存在复制代码
WeakSetThere are the following two differences compared with Set
- WeakSet can only be a collection of objects, not any value of any type
- WeakSet weak reference, the object reference in the collection is a weak reference. If there is no other reference to the WeakSet object, it will be recycled by GC
Finally, WeakRef instance has A method deref that returns the original object referenced, or undefined
const cache = new Map();const setValue = (key, obj) => { cache.set(key, new WeakRef(obj)); };const getValue = (key) => { const ref = cache.get(key); if (ref) { return ref.deref(); } };const fibonacciCached = (number) => { const cached = getValue(number); if (cached) return cached; const sum = calculateFibonacci(number); setValue(number, sum); return sum; };复制代码
if the original object is recycled. This may not be a good idea for caching remote data. idea, since remote data may be deleted from memory unpredictably. In this case it is better to use a cache like LRU.
Logical operators and assignment expressions
Logical operators and assignment expressions, the new feature combines logical operators (&&, ||, ??) and assignment expressions And JavaScript already exists Compound assignment operators are:
- Operation operators: = -= *= /= %= **=
- Bit operation operators: &= ^= | =
- Bitwise operators:<<= >>= >>>=
The existing operators can work in any way To understand the
expression like this: a op= b
is equivalent to: a = a op b
logical operator sum Other compound assignment operators work differently.
The expression: a op= b
is equivalent to: a = a op (a = b)
a ||= b//等价于a = a || (a = b) a &&= b//等价于a = a && (a = b) a ??= b//等价于a = a ?? (a = b)复制代码
为什么不再是跟以前的运算公式a = a op b一样呢,而是采用a = a op (a = b)。因为后者当且仅当a的值为false的时候才计算赋值,只有在必要的时候才执行分配,而前者的表达式总是执行赋值操作
??=可用来补充/初始化缺失的属性
const pages = [ { title:'主会场', path:'/' }, { path:'/other' }, ... ] for (const page of pages){ page.title ??= '默认标题'}console.table(pages)//(index) title path//0 "主会场" "/"//1 "默认标题" "/other"复制代码
小结:
- &&=:当LHS值存在时,将RHS变量赋值给LHS
- ||=:当LHS值不存在时,将RHS变量赋值给LHS
- ??= :当LHS值为null或者undefined时,将RHS变量赋值给LHS
数字分隔符
数字分隔符,可以在数字之间创建可视化分隔符,通过_下划线来分割数字,使数字更具可读性
const money = 1_000_000_000//等价于const money = 1000000000const totalFee = 1000.12_34//等价于const totalFee = 1000.1234复制代码
该新特性同样支持在八进制数中使用
const number = 0o123_456//等价于const number = 0o123456复制代码
该新特性方便读取数据,可以让我们打工人更容易辨认"资产" 不过话说回来,小编的资产好像不配使用该特性...敲重点!!!
本次所有新特性均介绍的第4阶段,意味着将出现在下一个版本中的,没有介绍阶段3的,因为不确定是否一定会出现在下个版本中。本文介绍的新特性均可直接在最新版的谷歌浏览器中愉快体验。
相关免费学习推荐:javascript(视频)
The above is the detailed content of Be the first to experience new features of JavaScript ES12. 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
