search
HomeWeb Front-endJS TutorialBe the first to experience new features of JavaScript ES12

The

JavaScript column introduces how to experience the new features of ES12.

Be the first to experience new features of JavaScript 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!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)