Originally, ES7~12 added these attributes respectively

ES6, also known as ES2015, was released in 2015. Since then, some attributes have been added every year, named ES7~12 re...

ES6, also known as ES2015, was released in 2015. Since then, some attributes have been added every year, named ES7~12 respectively. The release years correspond to 2016 to 2021 respectively

ES7

includes method

The include method is added to the array to judge whether an element exists in the array. Before this, indexOf is used to judge the subscript value. If it is less than 0, it means it does not exist.

const list = ['alice', 'kiki', 'macus'] console.log(list.includes('alice')) console.log(list.indexOf('alice')) console.log(list.includes('hello')) console.log(list.indexOf('hello'))

includes returns a Boolean value and indexOf returns the subscript of the array

Exponential operation

ES7 adds the operator of exponential operation, two * signs (* *), which are calculated by Math.pow before

const num = 3 const sqrt = Math.pow(num, 4) const result = num ** 4 console.log(sqrt, result)

The above represents the fourth power of num, and the execution results are all 81

**Math.pow is also used when the operator is compiled into es5 syntax through babel

ES8

Object.values and Object.entries

Object.keys (an attribute that existed before ES6) gets all the key values of the object. Object.values gets all the value values of the object. Object.entries returns an array containing an array of each key and value element

const obj = { name: 'alice', age: 18 } const list = ['alice', 'kiki', 'macus'] const messsage = 'hello' console.log(Object.keys(obj), Object.values(obj), Object.entries(obj)) console.log(Object.keys(list), Object.values(list), Object.entries(list)) console.log(Object.keys(messsage), Object.values(messsage), Object.entries(messsage))

Get the key and value of array, object and string and the array composed of key and value respectively

stringPadding

Use padStart and padEnd to fill the beginning and end of the string, and pass in the filled string length and filling content

const message = "hello world" const startMsg = message.padStart(15, '-') const endMsg = message.padEnd(16, '*') console.log(startMsg) console.log(endMsg) const nickName = 'stars' const firstName = nickName.substr(0, 1) const newName = firstName.padEnd(nickName.length, '*') console.log(newName)

Fill the beginning and end of the string and a small case

Trailing Commas

The trailing comma allows the function to add a comma (,) after the last parameter when defining formal parameters and passing parameters

function foo(a, b,){ console.log(a, b,) } foo(1,2,) function baz(m, n){ console.log(m, n) } baz('m', 'n',)

Adding a comma after the last parameter will not be considered wrong

getOwnPropertyDescriptors

Gets the description of all properties of the object

const obj = { name: 'alice', age: 18 } console.log(Object.getOwnPropertyDescriptors(obj))

Include enumerable, writable, configurable, and value values

other
  • async and await, which will be recorded in detail in later articles

ES9

All properties
  • iterators iterator, which will be recorded in detail in a later article
  • spread operators, object expansion operators, recorded in Do you know these properties in ES6 In this article
  • promise finally, put it together with promise in the following articles for detailed records

ES10

flat and flatMap

The flat function is used to reduce the dimension of the array. You only need to pass in the level that needs to be reduced

const array = [1, 2, [3, 4], [[5, 6], [7, 8], [9]], [10], 11, 11, 11, [12, [13, [14]]]] const num = array.flat(2) console.log(num)

At this time, the incoming dimension reduction level is 2, so the data of the four-dimensional array is reduced by two dimensions, and there are still two dimensions

The flatMap method will traverse the array first, and then reduce the dimension, which is equivalent to map+flat

const list = ["macus mogan", "arish sira", "linda kiki"] const result = list.flatMap(item => { const element = item.split(" ") console.log('Elements split each time:',element) return element }) console.log(result)

At this time, when traversing each group of elements, cut the space into an array, and the flatMap will directly reduce the dimension

Object.fromEntries

Object.fromEntries converts an array type such as entries into an object

const obj = { name: 'alice', age: 18 } const arr = ['alice', 'kiki', 'macus'] const str = 'hello' const objEntries = Object.entries(obj) const arrEntries = Object.entries(arr) const strEntries = Object.entries(str) console.log(objEntries) console.log(Object.fromEntries(objEntries)) console.log('--------------------------------------------------------------') console.log(arrEntries) console.log(Object.fromEntries(arrEntries)) console.log('--------------------------------------------------------------') console.log(strEntries) console.log(Object.fromEntries(strEntries))

Turn the object, array and string into entries respectively, and then turn them into objects through fromEntries. fromEntries is not a reverse Object.entries operation, and the type of array or string will not be restored

trimStart trimEnd

trim can be used to remove spaces at the beginning and end of the string. In ES10, trimstart and trimend are added to remove spaces at the beginning and end of the string respectively

const message = " hello world " const messageLen = message.length const trimMsg = message.trim() const trimStartMsg = message.trimStart() const trimEndMsg = message.trimEnd() console.log(messageLen) console.log(trimMsg, trimMsg.length) console.log(trimStartMsg, trimStartMsg.length) console.log(trimEndMsg, trimEndMsg.length)

Through the length of the string, you can judge whether the leading and trailing spaces are removed

other
  • The descriptor property of the Symbol, recorded in Do you know these properties in ES6 In this article
  • Optional catch binding, which will be recorded together in the later try catch article

ES11

bigInt

Before that, it indicates that large numbers can be used Number.MAX_SAFE_INTEGER, but there is a precision problem if this representation is to be calculated. ES11 adds a way to represent large numbers, and writes the letter N after the number, such as 1234567890987654321n.

But there are still some rules for this way of operation

  1. Large numbers with n cannot be operated on with small numbers without n

    • You can add an n directly after the small number
    • Or use the BigInt method to convert small numbers to large numbers
  2. There may be a loss of accuracy in converting large numbers to small numbers

const num = Number.MAX_SAFE_INTEGER console.log(num + 1) console.log(num + 2) const bigNum = 80082088208008208820n console.log(bigNum + 10n) console.log(bigNum + BigInt(10)) console.log(Number(bigNum))

Above Max_ SAFE_ Both integer operation and bigInt to Number have the problem of precision loss

Nullish Coalescing Operator

The null value merging operator (?) judges the Boolean value of the data. If the null and undefined data are judged to be false, the value behind the operator will be taken, and the or operator (|) judges to be false for null, undefined, empty string and 0

const nullStr = null; const undefinedStr = undefined; const string = ""; const number = 0; const user = {}; console.log(nullStr ?? "Nonexistent content", nullStr || "Nonexistent content"); console.log(undefinedStr ?? "Unrecognized type", undefinedStr || "Unrecognized type"); console.log(string ?? "Empty string", string || "Empty string"); console.log(number ?? "number", number || "number"); console.log(user ?? "Empty object", user || "Empty object");

The two are inconsistent only in the case of empty string and number 0

Optional Chining

The optional chain (?.) is used in the object to judge whether the data exists / can be read. Only when it is not null and undefined can it operate downward.

const user = { name: 'alice', favorite: { sport: 'tennis' } } console.log(user?.favorite?.sport) console.log(user && user.favorite && user.favorite.sport) console.log(user?.info?.address) console.log( user && user.info && user.info.address)

The effect achieved by the optional chain is the same as that achieved by the & & operator, but the code is more concise

globalThis

javascript code can run in the browser or nodejs. The two containers obtain global objects in different ways. They can use window or this in the browser and global on the node side. Es 11 is unified. Using globalThis, you can directly obtain global objects on both the browser side and the node side.

console.log(globalThis)

window objects are printed in the browser, and global objects are printed on the node side

other
  • For in is standardized. Before es11, there was no provision on whether to take key or value when traversing for in. Each browser has its own implementation. Es11 specifies the standard and needs to use key
  • Dynamic Import, which will be recorded in es modular articles
  • Promise.allSettled, will be recorded in promise's article
  • import meta, which will be recorded in the es modular article

ES12

FinalizationRegistry

It is used to specify a callback when the object is recycled by the garbage collector (GC) and register through the register

let user = { name: "alice", }; const registry = new FinalizationRegistry((value) => { console.log("The object was destroyed", value); }); registry.register(user, 'user') user = null

GC detects whether there is recyclable garbage from time to time. Therefore, when the object points to null, it will not immediately execute the function to obtain the callback. It cannot be tested in nodejs, but only in the browser, because the process will be closed when it is completed in nodejs. The browser is a process and will not be closed when it is running.

WeakRef

Directly assign object A to object B. they all point to A memory address 0x100. Because it is A strong reference at this time, 0x100 is still pointed to by B even after A points to null, so 0x100 will not be destroyed.

If you want 0x100 to be destroyed after A points to null, you can use weakRef to implement weak reference.

let user = { name: 'alice' } let info = new WeakRef(user) const registry = new FinalizationRegistry((value) => { console.log("The object was destroyed", value); }); registry.register(user, 'user') registry.register(info, 'info') user = null console.log(info, info.deref())

Create a weak reference through the new keyword and obtain data through the deref method. When the referenced object is recycled, the object generated by the weak reference cannot be obtained

logical assignment operators

Assignment logic operation is equivalent to the operation of assignment after logic operation

  • ||=Logical or assignment operation, or operation first, and then assignment
  • &&=Logic and assignment operation, and operation first, and then assignment
  • ??= In the logic null assignment operation, the null value is judged first and then assigned
let num = 0 // num = num + 1 is equivalent to the following num += 1 console.log(num) let message = '' // Message = message | 'hello' is equivalent to the following message ||= 'hello' console.log(message) let user = { name: 'alice' } // User = user & & user.name is equivalent to the following user &&= user.name console.log(user) let str = 0 // str = str ?? 'string 'is equivalent to the following str ??= 'string' console.log(str)

Logical assignment is like assignment after + = and + 1. It is a syntax sugar of operation

Numeric Separator

Number separator. Larger numbers can be separated by underscore () to make the code more readable

const momeny = 100_200_300_400_500 console.log(momeny)

The execution result will be de underlined and displayed in decimal data

replaceAll

replaceAll()   Method returns a new string that satisfies all requirements   pattern (first parameter)   All parts of have been replaced (second parameter)   Replace.

const message = "hello world"; console.log(message.replace("l", "*")); console.log(message.replaceAll("l", "*"));

replaceAll will replace all that meet the criteria, while replace will only replace the first one

The above are most of the attributes contained in ES7-12. There are still many places that developers need to master about js advanced. You can see other blog posts I wrote and keep updating~

4 December 2021, 20:40 | Views: 2040

Add new comment

For adding a comment, please log in
or create account

0 comments