In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the practical methods of ES6". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the practical methods of ES6"?
Array.prototype.includes
To determine whether an array contains an element, this is generally done before:
If (arr.indexOf (el) > = 0) {} / / or if (~ arr.indexOf (el)) {}
And now you can do this:
If (arr.includes (el)) {}
IndexOf returns the index position of the element in the array to determine whether the logic is strictly equal, so he cannot return the index correctly when he encounters NaN, but includes solves this problem:
[1, NaN, 3] .indexof (NaN) / /-1 [1, NaN, 3] .indexOf (NaN) / / true
Find the power operator (*)
X * * y is the y power of x, which is consistent with the Math.pow (x, y) function:
/ / x * * y let squared = 2 * 2 / / 2 * 2 = 4 let cubed = 2 * 3 / / 2 * 2 * 2 = 8
X * * = y means to find the y power of x and assign the result to x:
/ / x * * = y let x = 2; x * * = 3 / / x equals 8
ES2017
Object.values ()
Returns an array of property values of all traverable properties of the object itself:
Const person = {name: 'Bran'}; Object.defineProperty (person, 'age', {value: 12, enumrable: false / / age attribute will not be traverable}) console.log (Object.values (person)) / / [' Bran'] / / similar to str.split ('abc') console.log (Object.values (' abc')) / / ['await,' baked,'c']
Object.entries ()
Returns an array of key-value pairs of all traverable properties of the object itself:
Const person = {name: 'Bran', age: 12} console.log (Object.entries (person)) / / [[name "," Bran "], [" age ", 12]]
Using this method, you can convert the object into the current Map structure:
Const person = {name: 'Bran', age: 12} const map = new Map (Object.entries (person)) console.log (map) / / Map {name: 'Bran', age: 12}
Object.getOwnPropertyDescriptors ()
Object.getOwnPropertyDescriptor () returns a description object of one of the specified object's own properties, while Object.getOwnPropertyDescriptors () returns a description object of all its own properties:
Const person = {name: 'Bran', age: 12} console.log (Object.getOwnPropertyDescriptor (person, 'name')) / / {configurable: true, enumerable: true, value: "Bran", writable: true} console.log (Object.getOwnPropertyDescriptors (person)) / / {/ / name: {configurable: true, enumerable: true, value: "Bran", writable: true}, / / age: {configurable: false, enumerable: false, value: 12, writable: false} / /}
Shallow cloning can be achieved with Object.create ():
Const shallowClone = (obj) = > Object.create (Object.getPrototypeOf (obj), Object.getOwnPropertyDescriptors (obj))
String.prototype.padStart ()
Str.padStart (length [, padStr]) returns a new string that will fill a string padStr from the left side of the str string (optional; if it is not a string, it will be converted to a string. The effect of passing undefined is the same as not passing this parameter) until the specified number of digits length is reached:
'abc'.padStart (5, 2) / /' 22abc' 'abc'.padStart (5, undefined) / /' abc' 'abc'.padStart (5, {}) / /' [oabc' 'abc'.padStart (5) / /' abc' 'abcde'.padStart (2,' f') / / 'abcde'
String.prototype.padEnd ()
The rule is similar to padStart, but populates from the right side of the string:
'abc'.padEnd (5,2) / / 'abc22'
Function argument trailing comma
Allows functions to be defined and called with a comma after the last argument:
Function init (param1, param2,) {} init ('averse,' baked,)
Async function
Using async, you can declare an async function, and with await you can write Promise-based asynchronous behavior in a very brief way, without the need for deliberate chained calls. The await expression suspends the execution process of the entire async function and relinquishes control of it, resuming the process only after the Promise-based asynchronous operation it is waiting for is fulfilled or rejected. The async function is defined in the following forms:
/ / function declaration async function foo () {} / / function expression let foo = async function () {} / / Arrow function let foo = async () = > {} / / object method lef obj = {async foo () {}} / / Class method class Dog {async bark () {}}
The async function must return a Promise object, so it can use then to add handlers. If the return value of an async function does not appear to be Promise, it will be implicitly wrapped in a Promise:
Async function foo () {return 'a'} foo () .then (res = > {console.log (res) / /'a'})
If an internal error occurs, or if an error is displayed, the async function returns a Promsie with a rejected status:
Async function foo () {throw new Error ('error')} foo () .catch (err = > {console.log (err) / / Error: error})
The returned Promise object will not change its state until all internal await command Promise objects are executed, unless a return statement is encountered or an error is thrown; any Promise object returned by an await command becomes rejected, and the entire Async function will interrupt subsequent execution:
Async function fn () {let a = await Promise.resolve ('success') console.log (' console.log'+ a) let b = await Promise.reject ('fail') console.log (' baked'+ b) / / will not execute} fn (). Then (res = > {console.log (res) / / will not execute}, err = > {console.log (err)}) / / 'fail'' / /
So in order to ensure that all the asynchronous operations in async can be completed, we need to put them in the try...catch () block or follow the Promise returned by await with a catch handler:
Async function fn () {try {let a = await Promise.reject ('a fail') console.log ('a console.log'+ a) / / will not execute} catch (e) {console.log (e) / /'a fail'} let b = await Promise.reject ('b fail') .catch (e = > {console.log (e) ) / /'b fail'}) console.log ('baked' + b) / / 'bundefined'} fn (). Then (res = > {console.log (res) / / undefined}) Err = > {console.log (err) / / will not execute})
If there are no dependencies between multiple asynchronous operations in the async function, it is recommended that you write them together to reduce execution time:
/ / let [foo, bar] = await Promise.all ([getFoo (), getBar ()]) / / two let fooPromise = getFoo () let barPromise = getBar () let foo = await fooPromise let bar = await barPromise
The await command can only be used in async functions. If it is used in ordinary functions, an error will be reported.
Shared memory and Atomics objects
SharedArrayBuffer
Atomics
ES2018
Promise.prototype.finally ()
Promise.prototype.finally () is used to add an onFinally function to the Promise object, which mainly does some cleaning work, and the onFinally function is executed only when the state changes.
Function onFinally () {console.log (888) / / will not execute} new Promise ((resolve, reject) = > {}) .finally (onFinally)
Finally () generates a new instance of Promise, and the finally usually passes on the parent Promise as is, regardless of the status of the parent instance:
Let p1 = new Promise (() = > {}) let p2 = p1.finally (() = > {}) setTimeout (console.log, 0, p2) / / Promise {} let p3 = new Promise ((resolve, reject) = > {resolve (3)}) let p4 = p3.finally (() = > {}) setTimeout (console.log, 0, p3) / / Promise {: 3}
The above is general, but there are also special cases. For example, when a non-fulfilled Promise is returned in finally or an exception is thrown, a new instance of the corresponding status is returned:
Let p1 = new Promise ((resolve, reject) = > {resolve (3)}) let p2 = p1.finally (() = > new Promise (() = > {})) setTimeout (console.log, 0, p2) / / Promise {} let p3 = p1.finally (() = > Promise.reject (6)) setTimeout (console.log, 0, p3) / / Promise {: 6} let p4 = p1.finally (() = > {throw new Error ('error')}) setTimeout (console.log, 0) P4) / / Promise {: Error: error}
Reference:
Deep understanding of Promise
Asynchronous iterator
The best way to learn about asynchronous iterators is to compare them with synchronous iterators. We know that inside the iterable data, there is a Symbol.iterator property, which is a function that returns an iterator object after execution. This iterator object has a next () method to iterate over the data, and next () returns an object that contains the current iteration value value and the done property that identifies whether the iteration is completed:
Let iterator = [1,2] [Symbol.iterator] () iterator.next () / / {value: 1, done: false} iterator.next () / / {value: 2, done: false} iterator.next () / / {value: undefinde, done: true}
Next () above performs synchronous operations, so this is a synchronous iterator, but if you need to perform asynchronous operations in next (), you need to iterate asynchronously. There is a Symbol.asyncIterator attribute inside the data that can be iterated asynchronously, based on which we implement an asynchronous iterator:
Class Emitter {constructor (iterable) {this.data = iterable} [Symbol.asyncIterator] () {let length = this.data.length, index = 0; return {next: () = > {const done = index > = length const value =! done? This.data [index++]: undefined return new Promise ((resolve, reject) = > {resolve ({value, done})})}
The next () of the asynchronous iterator performs an asynchronous operation, usually returning a Promise, so the corresponding handler is needed to process the result:
Let emitter = new Emitter ([1,2,3]) let asyncIterator = emitter [Symbol.asyncIterator] () asyncIterator.next (). Then (res = > {console.log (res) / / {value: 1, done: false}}) asyncIterator.next (). Then (res = > {console.log (res) / / {value: 2, done: false}}) asyncIterator.next () .then (res = > {console.log (res) / / {value: 3, done: false})
Alternatively, you can use for await...of to iterate over asynchronous iterable data:
Let asyncIterable = new Emitter ([1,2,3]) async function asyncCount () {for await (const x of asyncIterable) {console.log (x)}} asyncCount () / / 1 2 3
You can also create an asynchronous iterator through an asynchronous generator:
Class Emitter {constructor (iterable) {this.data = iterable} async * [Symbol.asyncIterator] () {let length = this.data.length, index = 0; while (index
< length) { yield this.data[index++] } } } async function asyncCount() { let emitter = new Emitter([1, 2, 3]) const asyncIterable = emitter[Symbol.asyncIterator]() for await (const x of asyncIterable ) { console.log(x) } } asyncCount() // 1 2 3 参考: Iteration_protocols for-await...of s修饰符(dotAll模式) 正则表达式新增了一个 s 修饰符,使得 . 可以匹配任意单个字符: /foo.bar/.test('foo\nbar') // false /foo.bar/s.test('foo\nbar') // true 上面这又被称为 dotAll 模式,表示点(dot)代表一切字符。所以,正则表达式还引入了一个dotAll属性,返回一个布尔值,表示该正则表达式是否处在dotAll模式: /foo.bar/s.dotAll // true 具名组匹配 正则表达式可以使用捕获组来匹配字符串,但是想要获取某个组的结果只能通过对应的索引来获取: let re = /(\d{4})-(\d{2})-(\d{2})/ let result = re.exec('2015-01-02') // result[0] === '2015-01-02' // result[1] === '2015' // result[2] === '01' // result[3] === '02' 而现在我们可以通过给捕获组 (?...) 加上名字 name ,通过名字来获取对应组的结果: let re = /(?\d{4})-(?\d{2})-(?\d{2})/ let result = re.exec('2015-01-02') // result.groups.year === '2015' // result.groups.month === '01' // result.groups.day === '02' 配合解构赋值可以写出非常精简的代码: let {groups: {year, month, day}} = /(?\d{4})-(?\d{2})-(?\d{2})/.exec('2015-01-02') console.log(year, month, day) // 2015 01 02 具名组也可以通过传递给 String.prototype.replace 的替换值中进行引用。如果该值为字符串,则可以使用 $获取到对应组的结果: let re = /(?\d{4})-(?\d{2})-(?\d{2})/ let result = '2015-01-02'.replace(re, '$/$/$') // result === '02/01/2015' 参考: proposal-regexp-named-groups 后行断言 后行断言: (? 允许正则表达式匹配符合 Unicode 某种属性的所有字符,\p{...} 是匹配包含,\P{...}是匹配不包含的字符,且必须搭配 /u 修饰符才会生效: /\p{Emoji}+/u.exec('??笑死我了??不行了') // ['??'] /\P{Emoji}+/u.exec('??笑死我了??不行了') // ['笑死我了'] 这里可以查询到更多的 Unicode 的属性 Full_Properties 对象扩展运算符 对象的扩展运算符可以用到解构赋值上,且只能应用到最后一个变量上: let {x, ...y} = {x: 1, a: 2, b: 3} console.log(y) // {a: 2, b: 3} 对象扩展运算符不能解构原型上的属性: let obj = { x: 1 } obj.__proto__ = { y: 2 } let {...a} = obj console.log(a.y) // undefined 应用一:可以实现浅拷贝,但是不会拷贝原始属性: let person = Object.create({ name: '布兰' }) person.age = 12 // 浅拷贝写法一 let { ...pClone1 } = person console.log(pClone1) // { age: 12 } console.log(pClone1.name) // undefined // 浅拷贝写法二 let pClone2 = {...person} console.log(pClone2) // { age: 12 } console.log(pClone2.name) // undefined 应用二:合并两个对象: let ab = {...a, ...b} // 等同于 let ab = Object.assign({}, a, b); 应用三:重写对象属性 let aWithOverrides = { ...a, x: 1, y: 2 }; 应用四:给新对象设置默认值 let aWithDefaults = { x: 1, y: 2, ...a }; 应用五:利用扩展运算符的解构赋值可以扩展函数参数: function baseFunction({ a, b }) {} function wrapperFunction({ x, y, ...restConfig }) { // 使用 x 和 y 参数进行操作 // 其余参数传给原始函数 return baseFunction(restConfig) } 参考: Object Spread Initializer Object Rest Destructuring 放松对标签模板里字符串转义的限制 参考: ECMAScript 6 入门 ES2019 允许省略catch里的参数 异常被捕获的时候如果不需要做操作,甚至可以省略 catch(err) 里的参数和圆括号: try { } catch { } JSON.stringify()变动 UTF-8 标准规定,0xD800 到 0xDFFF 之间的码点,不能单独使用,必须配对使用。 所以 JSON.stringify() 对单个码点进行操作,如果码点符合 UTF-8 标准,则会返回对应的字符,否则会返回对应的码点: JSON.stringify('\u{1f600}') // ""?"" JSON.stringify('\u{D834}') // ""\ud834"" Symbol.prototype.description Symbol 实例新增了一个描述属性 description: let symbol = Symbol('foo') symbol.description // 'foo' Function.prototype.toString() 函数的 toString() 会原样输出函数定义时候的样子,不会省略注释和空格。 Object.fromEntries() Object.fromEntries() 方法是 Object.entries() 的逆操作,用于将一个键值对数组转为对象: let person = { name: '布兰', age: 12 } let keyValueArr = Object.entries(person) // [['name', '布兰'], ['age', 12]] let obj = Object.fromEntries(arr) // { name: '布兰', age: 12 } 常用可迭代数据结构之间的装换: let person = { name: '布兰', age: 12 } // 对象 ->Key-value array let keyValueArr = Object.entries (person) / [['name',' Bran'], ['age', 12]] / / key-value array-> Map let map = new Map (keyValueArr) / / Map {"name": "Bran", "age": 12} / / Map-> key-value array let arr = Array.from (map) / / [' name', 'Bran'], ['age'' 12]] / / key-value pair array-> object let obj = Array.from (arr). Reduce ((acc, [key, val]) = > Object.assign (acc, {[key]: val}), {}) / {name: 'Bran', age: 12}
Reference:
Object.fromEntries
Strings can be directly entered into line delimiters and segment separators
JavaScript stipulates that there are 5 characters, which cannot be used directly in the string, but can only be used in escape form.
Uzz005C: backslash (reverse solidus)
Utt000D: enter (carriage return)
Uplink 2028: line separator (line separator)
Segment Delimiter (paragraph separator)
Uzz000A: newline character (line feed)
However, since JSON allows Ubun2028 and Ubun2029 to be used in strings, it may cause errors when JSON.parse () parses strings, so ES2019 allows these two characters to be directly used in template strings:
JSON.parse ('"\ u2028") / / "" JSON.parse ('"\ u2029"') / / "" JSON.parse ('"\ u005C"') / / SyntaxError
String.prototype.trimStart
Remove the header space of the string and return a new string; the browser also adds its alias function trimLeft ():
Let str = 'hello world' let newStr = str.trimStart () console.log (newStr, newStr = str) / / 'hello world' false
String.prototype.trimEnd
Eliminate the trailing space of the string and return a new string; the browser also adds its alias function trimRight ():
Let str = 'hello world' let newStr = str.trimEnd () console.log (newStr, newStr = str) / /' hello world' false
Array.prototype.flat ()
Arr.flat (depth) flattens an array according to the depth of depth (default is 1 if no value is passed) and returns the result as a new array:
/ / depth defaults to 1 const arr1 = [1, 2, [3, 4]] console.log (arr1.flat ()) / / [1, 2, 3, 4] / / use Infinity to expand nested arrays of arbitrary depth; automatically skip empty arrays; const arr2 = [1, [2, [3, [4] console.log (arr2.flat (Infinity)) / / [1,2,3,4]
Use reduce to flatten one-layer array:
Const arr = [1,2, [3,4]] / method one let newStr = arr.reduce ((acc, cur) = > acc.concat (cur), []) / / method two const flattened = arr = > [] .concat (... arr) flattened (arr)
Reference:
Flat
Array.prototype.flatMap ()
FlatMap (callback) uses the mapping function callback to map each element, and each return value of callback forms an array, and the array is flattened by performing an operation similar to arr.flat (1), and the final result is returned:
Const arr1 = [1,2,3,4] arr1.flatMap (x = > [x * 2]) / / flatten the array [[2], [4], [6], [8] to get the final result: [2,4,6,8]
Reference:
FlatMap
ES2020
String.prototype.matchAll ()
The String.prototype.matchAll () method, which can fetch all matches at once. However, it returns a RegExpStringIterator iterator that is also an iterable data structure, so you can iterate through for...of:
Let str = 'test1test2' let regexp = / t (e) (st (\ d?)) / g let iterable = str.matchAll (regexp) for (const x of iterable) {console.log (x)} / / [' test1', 'eBay,' st1','1', index: 0, input: 'test1test1', groups: undefined] / / [' test2', 'eBay,' st2','2', index: 5, input: 'test1test2', groups: undefined]
❝notes that when using matchAll (regexp), regular expressions must be modified with the / g modifier. ❞
You can also convert this iterable data into an array:
/ / method 1 [... str.matchAll (regexp)] / / method 2 Array.from (str.matchAll (regexp))
Dynamic import ()
The module imported by the standard import is static and causes all imported modules to be compiled at load time (unable to compile on demand, slowing down the home page loading speed). In some scenarios, you may want to import modules according to conditions or on demand, and you can use dynamic imports instead of static imports.
For example, you can load a module on demand like this:
If (xxx) {import ('. / module.js')}
Import () is imported asynchronously, and the result returns a Promise:
Import ('/ module.js'). Then (module) = > {/ / Do something with the module. })
There are many application scenarios for dynamic import (). For example, routing lazy loading in Vue is a dynamic import component used. In addition, because the dynamic nature is not convenient for static analysis tools and tree-shaking work, it can not be abused.
BigInt
BigInt is a built-in object that provides a way to represent integers greater than-1. This was originally the largest number that could be represented in Number in Javascript. BigInt can represent any large integer.
To distinguish between Number, to define a BigInt, you need to add an n to the integer, or define it directly with a function:
Const num1 = 10n const num2 = BigInt (20)
Number and BigInt can be compared, but they are loosely equal, and because they represent different types of numbers, four operations cannot be performed directly:
10n = = 10 / / true 10n = = 10 / / false 10n > 8 / / true 10 + Number (10n) / / 20 10 + 10n / / TypeError
Promise.allSettled
Promise.allSettled (iterable) when all instances have been settled, that is, the state has changed, a new instance will be returned. The internal value of the new instance is an array of values and states of all instances, and each item of the array is an object composed of the state and internal values of each instance.
Function init () {return 3} let p1 = Promise.allSettled ([new Promise ((resolve, reject) = > {resolve (9)}) .then (res = > {}), new Promise ((resolve, reject) = > {reject (6)}), init () let p2 = p1.then (res = > {console.log (res)}) Err = > {console.log (err)}) / [/ / {status: "fulfilled", value: undefined}, / / {status: "rejected", reason: 6}, / / {status: "fulfilled", value: 3} / /]
As long as all instances contain an instance of pending status, the result of Promise.allSettled () is to return an instance of such Promise {}.
GlobalThis
Previously, getting global objects from different JavaScript environments required different statements. In Web, global objects can be fetched through window, self, or frames, but in Web Workers, only self can. In Node.js, none of them can be obtained, so you must use global.
Now you only need to use globalThis to get the top-level objects without worrying about the environment.
/ / in the browser globalThis = window / / true
Import.meta
Import.meta is an object that exposes metadata attributes of a particular context to a JavaScript module. It contains information about the module, for example, the URL,import.meta of this module must be used in a module:
/ / without declaring type= "module", using import.meta will report an error / / console.log (import.meta) / / {url: "http://localhost/3ag/js/module.js"} in module.js
If you need to use import.meta in a project that is configured with Webpack, such as Vue, you need to add a package and configure the parameters, otherwise the project will report an error during the compilation phase.
For more information on package configuration, please see:
@ open-wc/webpack-import-meta-loader
For example, if I use the 4.x version of vue-cli, then I need to configure it in vue.config.js:
Module.exports = {chainWebpack: config = > {config.module .rule ('js') .test (/\ .js $/) .use (' @ open-wc/webpack-import-meta-loader') .loader ('@ open-wc/webpack-import-meta-loader') .end ()}}
Optional chain operator (?)
Usually we need to write a lot of judgments or use logic and & & operators to obtain the properties of a deep object, because an error may be reported if a property of the object is null or undefined:
Let obj = {first: {second: 'Bran'}} / / let name1 =''if (obj) {if (obj.first) {name1 = obj.first.second}} / / let name2 = obj & & obj.first & & obj.first.second
?. Operator allows you to read the value of a property deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid. If a property is null or undefined, the result is directly undefined. Having an optional chain operator can make the expression more concise, as can be written with the optional chain operator for the above example:
Let name3 = obj?.first?.second
Null merge operator (?)
For logical or | | operator, when the Operand on the left side of the operator is replaced with the value of Boolean, if it is true, the Operand on the left is taken as the result, otherwise the Operand on the right is taken as the result:
Let name =''| | 'Bran' console.log (name) / / 'Bran'
We all know that'', 0, null, undefined, false, NaN, etc. are all false when converted to Boolean values, so they all take the Operand on the right. At this time, if you want to set the default value for the variable, if you encounter a situation where the value itself may be''or 0, it will make an error and will be mistakenly set to the default value.
And?? Operators are created to solve this problem, x? Take the right Operand only if the left Operand is null or undefined, otherwise take the left Operand:
Let num = 0? 1 console.log (num) / / 0
ES2021
The following proposals have been confirmed to be released in 2021, so put them into ES2021.
String.prototype.replaceAll
Before you need to replace all matching characters in a string, you can do this:
Method 1 const withSpaces1 = queryString.replace (/\ + / g,'') / / method 2 const withSpaces2 = queryString.split ('+'). Join ('')
And now all you have to do is:
Const withSpace3 = queryString.replaceAll ('+','')
The first parameter of ❝replaceAll can be a string or a regular expression, and when it is a regular expression, you must add the global modifier / g, otherwise an error will be reported. ❞
Reference:
String-replaceall
Promise.any ()
Promsie.any () accepts an iterable object like Promise.all (), and then returns different new instances according to different participants:
If an empty iterable object or iterable object is passed with all Promise in rejected state, an error of type AggregateError will be thrown and a new instance of rejected status will be returned:
Let p1 = Promise.any ([]) let p2.catch (err = > {}) setTimeout (console.log, 0, p1) / / Promise {: AggregateError: All promises were rejected}
As long as the iterable object contains any Promise with a fulfilled state, the first instance of fulfilled is returned with its value as the value of the new instance:
Let p = Promise.any ([1, Promise.reject (2), new Promise ((resolve, reject) = > {}), Promise.resolve (3),]) setTimeout (console.log, 0, p) / / Promise {: 1}
In other cases, an instance of pending status is returned:
Let p = Promise.any ([Promise.reject (2), Promise.reject (3), new Promise ((resolve, reject) = > {}),] setTimeout (console.log, 0, p) / / Promise {: undefined}
WeakRef
We know that a normal reference (the default is a strong reference) will keep the corresponding object in memory. Only if the object does not have any strong references will the JavaScript engine GC destroy the object and reclaim the memory space occupied by the object.
The WeakRef object allows you to keep a weak reference to another object without preventing the weakly referenced object from being recycled by GC. The instance method deref () of WeakRef returns the target object bound by the WeakRef object of the current instance, or undefined if the target object has been recycled by GC:
Let person = {name: 'Bran', age: 12} let wr = new WeakRef (person) console.log (wr.deref ()) / {name: 'Bran', age: 12}
The correct use of WeakRef objects by ❝requires careful consideration and is best avoided. There are many reasons for this, such as: the behavior of GC in one JavaScript engine may be very different in another JavaScript engine, or even in the same type of engine, there may be significant differences in the behavior of GC in different versions. GC is currently a challenge for JavaScript engine implementers to constantly improve and improve solutions. ❞
Reference:
WeakRef
Memory management
Logical assignment character
The logical assignment character consists of three:
X & & = y: logic and assignment, equivalent to x & & (x = y)
X | | = y: logic or assignment character, equivalent to x | (x = y)
X? = y: logical empty assignment, equivalent to x? (X = y)
Look at the following example to deepen your understanding:
Let x = 0 x & & = 1 / / x: 0 x | | = 1 / / x: 1 x?? = 2 / / x: 1 let y = 1 y & & = 0 / / y: 0 y | | = null / / y: null y?? = 2 / / y: 2
Numeric delimiter (_)
For the following string of numbers, you don't seem sure what it is at first glance, do you?
Const num = 1000000000
What about now? Can you clearly see that it is 1 billion:
Const num = 1,000,000,000
The purpose of the numeric delimiter (_) is to make the value more readable. In addition to decimal, it can also be used in binary, hexadecimal, or even BigInt types:
Let binarary = 0b1010_0001_1000_0101 let hex = 0xA0_B0_C0 let budget = 1000000000000n
When using, you must note that there must be a type of value on both sides of _, otherwise an error will be reported. The following are invalid words:
Let num = 10 _ let binarary = 0b1011 _ let hex = 0x_0A0B let budget = 1 thank you for reading, these are the contents of "what are the practical methods of ES6?" after the study of this article, I believe you have a deeper understanding of what the practical methods of ES6 have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.