Home  >  Article  >  Web Front-end  >  Be the first to experience new features of JavaScript ES12

Be the first to experience new features of JavaScript ES12

coldplay.xixi
coldplay.xixiforward
2020-11-03 17:20:432666browse

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.im. If there is any infringement, please contact admin@php.cn delete