As a kid who likes to type code by hand, I think the code should be typed by myself in order to better memorize it by heart, so today I will introduce the features of ES6 ~ ES12. If you have blind spots in the use of ES, or don’t know much about the new features , I believe this article should be able to help you very well~
In order to better understand, we will explain it in case mode, so as to have a better understanding, and at the same time , the case also supports debugging in developer mode, I hope you can support it~
ECMAScript is a script programming language standardized by Ecma International (formerly the European Computer Manufacturers Association) through ECMA-262 . It can also be said that there are only two versions of JavaScript as a standard
in the world of programmers: ES5
and ES6
. It is said that ES6 was actually released in 2015, which is also the time when the big front-end era officially started. That is to say, 2015 is used as the year. Boundary, before 2015, it was called ES5
, and after 2016, it is collectively called ES6
For information about ES6
features, you can read "Introduction to ES6 Standards" by Teacher Ruan Yifeng.
The difference between let, const and var:
In addition, when an object is declared with const
, the properties of the object can be changed, because: obj declared by const only saves the reference address of its object. As long as the address remains unchanged, there will be no error
...
to represent all the remaining onesundefined
let [a, b, c] = [1, 2, 3] console.log(a, b, c) // 1 2 3 let [a, , c] = [1, 2, 3] console.log(a, , c) // 1 3 let [a, b, ...c] = [1, 2, 3, 4, 5] console.log(a, b, c) // 1 2 [3, 4, 5] let [a, b, ...c] = [1] console.log(a, b, c) // 1 undefined [] let [a = 1, b = a] = [] const.log(a, b) // 1 1 let [a = 1, b = a] = [2] const.log(a, b) // 2 2
undefined
:
, others Equivalent to the aliaslet { a, b } = { a: 1, b: 2 }; console.log(a, b); // 1 2 let { a } = { b: 2 }; console.log(a); // undefined let { a, b = 2 } = { a: 1 }; console.log(a, b); // 1 2 let { a: b = 2 } = { a: 1 }; console.log(a); // The variable a does not exist console.log(b); // 1
length
attribute. , representing the numberlet [a, b, c, d, e] = "hello" console.log(a, b, c, d, e) // hello let { length } = "hello" console.log(length) // 5
let { toString: s } = 123; console.log(s === Number.prototype.toString) // true let { toString: s } = true; console.log(s === Boolean.prototype.toString) // true
let arr = [[1,2], [3, 4]] let res = arr.map([a, b] => a + b) console.log(res) // [3, 7] let arr = [1, undefined, 2] let res = arr.map((a = 'test') => a); console.log(res) // [1, 'test', 2] let func = ({x, y} = {x: 0, y: 0}) => { return[x, y] } console.log(func(1, 2)) // [undefined, undefined] console.log(func()) // [0, 0] console.log(func({})) // [undefined, undefined] console.log(func({x: 1})) // [1, undefined] let func = ({x=0, y=0}) => { return[x, y] } console.log(func({x:1,y:2})) // [1, 2] console.log(func()) // error console.log(func({})) // [0, 0] console.log(func({x: 1})) // [1, 0]
regularity is actually a very difficult knowledge point to understand. If someone can fully master it, it is really very powerful. Let’s make it simple here
Firstof all,
it is divided into two styles: JS分格
and perl 分格
JS grid: RegExp()
let re = new RegExp('a'); //Find whether there is a in a string let re = new RegExp('a', 'i'); //The first is the search object, the second is the option
perl style: / rule/option, and can be followed by multiple, regardless of order
let re = /a/; //Find whether there is a in a string let re = /a/i;//The first is the object to be searched for, the second is the option.
Here we introduce a regular expression online test (with common regular expressions): Regular online test
大括号包含
the Unicode characters//Unicode console.log("a", "u0061"); // aa console.log("d", "u{4E25}"); // d strictly let str = 'Domesy' //codePointAt() console.log(str.codePointAt(0)) // 68 //String.fromCharCode() console.log(String.fromCharCode(68)) // D //String.raw() console.log(String.raw`Hin${1 + 2}`); // Hin3 console.log(`Hin${1 + 2}`); // Hi 3 let str = 'Domesy' //startsWith() console.log(str.startsWith("D")) // true console.log(str.startsWith("s")) // false //endsWith() console.log(str.endsWith("y")) // true console.log(str.endsWith("s")) // false //repeat(): The passed parameter will be automatically rounded up. If it is a string, it will be converted into a number console.log(str.repeat(2)) // DomesyDomesy console.log(str.repeat(2.9)) // DomesyDomesy // Traversal: for-of for(let code of str){ console.log(code) // Return D omesy once } //includes() console.log(str.includes("s")) // true console.log(str.includes("a")) // false // trimStart() const string = " Hello world! "; console.log(string.trimStart()); // "Hello world! " console.log(string.trimLeft()); // "Hello world! " // trimEnd() const string = " Hello world! "; console.log(string.trimEnd()); // "Hello world!" console.log(string.trimRight()); // "Hello world!"
let str = `Dome sy` console.log(str) //Will automatically wrap lines//Dome // sy
const str = { name: 'Little Dudu', info: 'Hello everyone' } console.log(`${str.info}, I am `${str.name}`) // Hello everyone, I am Xiao Dudu
let arr = [1, 2, 3, 4, 5] //Array.of() let arr1 = Array.of(1, 2, 3); console.log(arr1) // [1, 2, 3] //copyWithin(): three parameters (target, start = 0, end = this.length) // target: the position of the target // start: the starting position, which can be omitted and can be a negative number. // end: end position, can be omitted, can be a negative number, the actual position is end-1. console.log(arr.copyWithin(0, 3, 5)) // [4, 5, 3, 4, 5] //find() console.log(arr.find((item) => item > 3 )) // 4 //findIndex() console.log(arr.findIndex((item) => item > 3 )) // 3 //keys() for (let index of arr.keys()) { console.log(index); // Return 0 1 2 3 4 at a time } // values() for (let index of arr.values()) { console.log(index); // Return 1 2 3 4 5 at a time } // entries() for (let index of arr.entries()) { console.log(index); // Return [0, 1] [1, 2] [2, 3] [3, 4] [4, 5] once } let arr = [1, 2, 3, 4, 5] // Array.from(): The traversal can be a pseudo array, such as String, Set structure, Node node let arr1 = Array.from([1, 3, 5], (item) => { return item * 2; }) console.log(arr1) // [2, 6, 10] // fill(): three parameters (target, start = 0, end = this.length) // target: the position of the target // start: the starting position, which can be omitted and can be a negative number. // end: end position, can be omitted, can be a negative number, the actual position is end-1. console.log(arr.fill(7)) // [7, 7, 7, 7, 7] console.log(arr.fill(7, 1, 3)) // [1, 7, 7, 4, 5] let arr = [1, 2, 3, 4] //includes() console.log(arr.includes(3)) // true console.log([1, 2, NaN].includes(NaN)); // true
// Its function is to expand the array let arr = [3, 4, 5] console.log(...arr) // 3 4 5 let arr1 = [1, 2, ...arr] console.log(...arr1) // 1 2 3 4 5
for-in
//Object.is() console.log(Object.is('abc', 'abc')) // true console.log(Object.is([], [])) // false //Traverse: for-in let obj = { name: 'Domesy', value: 'React' } for(let key in obj){ console.log(key); // Return the attribute value name value in turn console.log(obj[key]); // Return the attribute values in sequence Domesy React } //Object.keys() console.log(Object.keys(obj)) // ['name', 'value'] //Object.assign() const target = { a: 1, b: 2 }; const source = { b: 4, c: 5 }; const result = Object.assign(target, source) console.log(result) // {a: 1, b: 4, c: 5} console.log(target) // {a: 1, b: 4, c: 5}
let a = 1; let b = 2; let obj = { a, b } console.log(obj) // { a: 1, b: 2 } let method = { hello() { console.log('hello') } } console.log(method.hello()) // hello
let a = "b" let obj = { [a]: "c" } console.log(obj) // {b : "c"}
// Its function is to expand the array let { a , b, ...c } = { a: 1, b: 2, c: 3, d: 4}; console.log(c) // {c: 3, d: 4} let obj1 = { c: 3 } let obj = { a: 1, b: 2, ...obj1} console.log(obj) // { a: 1, b: 2, c: 3}
0b
or 0B
, indicating binary00
or 0O
, indicating binary正数为1
numeric type正数为1
,负数为-1
,正零0
,负零-0
, NaN
parseInt
parseFloat
//Binary console.log(0b101) // 5 console.log(0o151) //105 //Number.isFinite() console.log(Number.isFinite(7)); // true console.log(Number.isFinite(true)); // false //Number.isNaN() console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN("true" / 0)); // true console.log(Number.isNaN(true)); // false //Number.isInteger() console.log(Number.isInteger(17)); // true console.log(Number.isInteger(17.58)); // false //Number.isSafeInteger() console.log(Number.isSafeInteger(3)); // true console.log(Number.isSafeInteger(3.0)); // true console.log(Number.isSafeInteger("3")); // false console.log(Number.isSafeInteger(3.1)); // false //Math.trunc() console.log(Math.trunc(13.71)); // 13 console.log(Math.trunc(0)); // 0 console.log(Math.trunc(true)); // 1 console.log(Math.trunc(false)); // 0 //Math.sign() console.log(Math.sign(3)); // 1 console.log(Math.sign(-3)); // -1 console.log(Math.sign(0)); // 0 console.log(Math.sign(-0)); // -0 console.log(Math.sign(NaN)); // NaN console.log(Math.sign(true)); // 1 console.log(Math.sign(false)); // 0 //Math.abrt() console.log(Math.cbrt(8)); // 2 //Number.parseInt() console.log(Number.parseInt("6.71")); // 6 console.log(parseInt("6.71")); // 6 //Number.parseFloat() console.log(Number.parseFloat("6.71@")); // 6.71 console.log(parseFloat("6.71@")); // 6.71
//The parameter is assigned a specific value by default. let x = 1 function fun(x, y = x){ console.log(x, y) } function fun1(c, y = x){ console.log(c, x, y) } fun(2); //2 2 fun1(1); //1 1 1
function fun(...arg){ console.log(arg) // [1, 2, 3, 4] } fun(1, 2, 3, 4)
let arrow = (v) => v + 2 console.log(arrow(1)) // 3
The difference between arrow functions and ordinary functions.
Set is a new data structure in ES6, which is similar to an array, but the value of the member is unique and there are no repeated value
declarations. : const set = new Set()
Attributes:
Method:
specifically Note:
iterator
object. In the order of insertion,let list = new Set() //add() list.add("1") list.add(1) console(list) // Set(2) {1, "1"} //size console(list.size) // 2 //delete() list.delete("1") console(list) // Set(1) {1} //has() list.has(1) // true list.has(3) // false //clear() list.clear() console(list) // Set(0) {} let arr = [{id: 1}, {id: 2}, {id: 3}] let list = new Set(arr) //keys() for (let key of list.keys()) { console.log(key); // Print this: {id: 1} {id: 2} {id: 3} } //values() for (let key of list.values()) { console.log(key); // Print this: {id: 1} {id: 2} {id: 3} } //entries() for (let data of list.entries()) { console.log(data); // Print this: [{id: 1},{id: 1}] [{id: 2},{id: 2}] [{id: 3},{id: 3 }] } //forEach list.forEach((item) => { console.log(item)//Print this: {id: 1} {id: 2} {id: 3} });
Application:
new Set
cannot remove objects.let arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a']; console.log([...new Set(arr)]) //or console.log(Array.from(new Set(arr))) // [1, 'true', true, 15, false, undefined, null, NaN, 'NaN', 0, 'a']
let a = new Set([1, 2 , 3]) let b = new Set([2, 3, 4]) //Union console.log(new Set([...a, ...b])) // Set(4) {1, 2, 3, 4} //Intersection console.log(new Set([...a].filter(v => b.has(v)))) // Set(2) {2, 3} //Difference set new Set([...a].filter(v => !b.has(v))) // Set(1) {1}
let set = new Set([1,2, 3]) console.log(new Set([...set].map(v => v * 2))) // Set(3) {2, 4, 6}
definition: The same structure as Set, but the member values are only Can
be declared for the object: const set = new WeakSet()
method:
Note:
recommendation index: ⭐️⭐️
Map is a new data structure in ES6, which is a similar object. The member key is a value declaration of any type
: const map = new Map()
attributes:
Method:
Special note:
let map = new Map() //set() map.set('a', 1) map.set('b', 2) console.log(map) // Map(2) {'a' => 1, 'b' => 2} //get map.get("a") // 1 //size console.log(map.size) // 2 //delete() map.delete("a") // true console.log(map) // Map(1) {'b' => 2} //has() map.has('b') // true map.has(1) // false //clear() map.clear() console.log(map) // Map(0) {} let arr = [["a", 1], ["b", 2], ["c", 3]] let map = new Map(arr) //keys() for (let key of map.keys()) { console.log(key); // Print this: abc } //values() for (let value of map.values()) { console.log(value); // Print this: 1 2 3 } //entries() for (let data of map.entries()) { console.log(data); // Print this: ["a", 1] ["b", 2] ["c", 3] } //forEach map.forEach((item) => { console.log(item)//Print this: 1 2 3 });
definition: and Map structure, but member values can only
be declared for objects: const set = new WeakMap()
method:
Symbol is a primitive data type introduced in ES6, which represents独一无二
Declaration
: const sy = Stmbol()
Parameters: string (optional)
Method:
Symbol值
described by parameters. If this parameter exists, return the original Symbol值
(search first and then create, Registered in the global environment)Symbol值
(only key
of Symbol.for()
can be returned)Symbol值
used as property names in the object// Declare let a = Symbol(); let b = Symbol(); console.log(a === b); // false //Symbol.for() let c = Symbol.for("domesy"); let d = Symbol.for("domesy"); console.log(c === d); // true //Symbol.keyFor() const e = Symbol.for("1"); console.log(Symbol.keyFor(e)); // 1 //Symbol.description let symbol = Symbol("es"); console.log(symbol.description); //es console.log(Symbol("es") === Symbol("es")); // false console.log(symbol === symbol); // true console.log(symbol.description === "es"); // true
Proxy is used to modify the default behavior of certain operations, which is equivalent to making changes at the language level, so it is a kind of "meta programming" ), that is, programming in a programming language
can be understood in this way. Proxy is a layer of拦截
set before the target object. The outside world must go through this layer of interception if they want to access it. Therefore, a mechanism is provided to filter and filter access from the outside world. rewrite.
Proxy can be understood here as代理器
declaration: const proxy = new Proxy(target, handler)
the method of interception:
let obj = { name: 'domesy', time: '2022-01-27', value: 1 } let data = new Proxy(obj, { //get() get(target, key){ return target[key].replace("2022", '2015') }, //set() set(target, key, value) { if (key === "name") { return (target[key] = value); } else { return target[key]; } }, // has() has(target, key) { if (key === "name") { return target[key]; } else { return false; } }, //deleteProperty() deleteProperty(target, key) { if (key.indexOf("_") > -1) { delete target[key]; return true; } else { return target[key]; } }, // ownKeys() ownKeys(target) { return Object.keys(target).filter((item) => item != "time"); }, }) console.log(data.time) // 2015-01-27 data.time = '2020' data.name = 'React' console.log(data) //Proxy {name: 'React', time: '2022-01-27', value: 1} //Intercept has() console.log("name" in data) // true console.log("time" in data) // false // Delete deleteProperty() delete data.time; // true // Traverse ownKeys() console.log(Object.keys(data)); //['name', 'value'] //apply() let sum = (...args) => { let num = 0; args.forEach((item) => { num += item; }); return num; }; sum = new Proxy(sum, { apply(target, ctx, args) { return target(...args) * 2; }, }); console.log(sum(1, 2)); // 6 console.log(sum.call(null, 1, 2, 3)); // 12 console.log(sum.apply(null, [1, 2, 3])); // 12 //constructor() let User = class { constructor(name) { this.name = name; } } User = new Proxy(User, { construct(target, args, newTarget) { return new target(...args); }, }); console.log(new User("domesy")); // User {name: 'domesy'}
Reflect is similar to Proxy, except that it keeps the default behavior of Object
and
Reflect's methods and The methods of Proxy correspond one to one, so we will not introduce them here.
Class: abstraction of a class of things with common characteristics (constructor syntax sugar)
class Parent { constructor(name = 'es6'){ this.name = name } } let data = new Parent('domesy') console.log(data) // Parent { name: 'domesy'}
class Parent { constructor(name = 'es6'){ this.name = name } } // Ordinary inheritance class Child extends Parent {} console.log(new Child()) // Child { name: 'es6'} // Pass parameters class Child extends Parent { constructor(name = "child") { super(name); this.type = "child"; } } console.log(new Child('domesy')) // Child { name: 'domesy', type: 'child'}The two methods
class Parent { constructor(name = 'es6'){ this.name = name } // getter get getName() { return 'sy' + this.name } // setter set setName(value){ this.name = value } } let data = new Parent() console.log(data.getName) // syes6 data.setName = 'domesy' console.log(data.getName) // domesy
class Parent { static getName = (name) => { return `Hello! ${name}` } } console.log(Parent.getName('domesy')) // Hello! domesy
class Parent {} Parent.type = "test"; console.log(Parent.type); //test
Promise
is to solve the "callback hell" problem. It can make the processing of asynchronous operations very elegant.
Promise
can support multiple concurrent requests and obtain data in concurrent requests. This Promise
can solve the asynchronous problem. Promise
itself cannot be said to be asynchronous
definition: Object status containing asynchronous operation results
:
Note:
//Normal definition let ajax = (callback) => { console.log('≈') setTimeout(() => { callback && callback.call(); }, 1000) } ajax(() => { console.log('timeout') }) // First it will be printed to start execution, then timeout will be printed after 1s. //Promise let ajax = () => { console.log("Start execution"); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }; ajax().then(() => { console.log("timeout"); }); // First it will be printed to start execution, then timeout will be printed after 1s. //then() let ajax = () => { console.log("Start execution"); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }; ajax() .then(() => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 2000); }); }) .then(() => { console.log("timeout") }) // First it will be typed to start execution, then timeout will be typed after 3s (1+2) // catch() let ajax = (num) => { console.log("Start execution"); return new Promise((resolve, reject) => { if (num > 5) { resolve(); } else { throw new Error("An error occurred"); } }); }; ajax(6) .then(function () { console.log("timeout"); // Will start execution first, then timeout will be printed after 1s }) .catch(function (err) { console.log("catch", err); }); ajax(3) .then(function () { console.log("timeout"); }) .catch(function (err) { console.log("catch"); // Will start execution first, then catch after 1s. });
//Add to the page after all images are loaded const loadImg = (src) => { return new Promise(resolve, reject) => { let img = document.createElement("img"); img.src = src; img.onload = function () { resolve(img); }; img.onerror = function (err) { reject(err); }; }); } const showImgs = (imgs) => { imgs.forEach((img) => { document.body.appendChild(img); }) } Promise.all([ loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), ]).then(showImgs);
// and loaded back to the page after one execution const loadImg = (src) => { return new Promise(resolve, reject) => { let img = document.createElement("img"); img.src = src; img.onload = function () { resolve(img); }; img.onerror = function (err) { reject(err); }; }); } const showImgs = (imgs) => { let p = document.createElement("p"); p.appendChild(img); document.body.appendChild(p); } Promise.race([ loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), loadImg("https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/71cf3bc79f3df8dcc6551159cd11728b46102889.jpg"), ]).then(showImgs);Once
Generator: Yes The function that can be used to control the iterator is also an asynchronous programming solution that encapsulates multiple internal states. It is also called the generator function
parameter description
.value
and done
value
represents the value, and done
returns Boolean (if it is false, it means there is more to follow, and if it is true, it has been completed)恢复
program execution.let data = function* (){ yield "a"; yield "b"; return "c" } let generator = data(); console.log(generator.next()) //{value: 'a', done: false} console.log(generator.next()) //{value: 'b', done: false} console.log(generator.next()) //{value: 'c', done: true} console.log(generator.next()) //{value: undefined, done: true}
Iterator is an interface that provides a unified access mechanism for various data structures. As long as any data structure deploys the Iterator interface, it can complete the traversal operation (that is, process all members of the data structure in sequence).
The functions of Iterator:
Note:
数组
,某些类似数组的对象
, Set
and Map结构
.//Basically use let arr = ["hello", "world"]; let map = arr[Symbol.iterator](); console.log(map.next()); // {value: 'hello', done: false} console.log(map.next()); // {value: 'world', done: false} console.log (map.next ()); // {value: undefined, do: true} // for of cycling let arr = ["hello", "world"]; for (Let Value of Arr) { console.log (value); // Hello World } // Object treatment Let obj = { Start: [1, 5, 2],, END: [7, 9, 6], [Symbol.iterator](){ let index = 0; let arr = this.start.concat (this.end) return { next(){ ifx <arr.Length) { return { Value: Arr [Index ++], Done: false } }else{ return { Value: Arr [Index ++], done: true } } } } } } for (let key of obj) { console.log (key); // 1 5 2 7 9 6 6 }
core-decorators
@
modified behavior,name = (target) => {{{{{ target.name = "domesy" } @name class test {} Console.log (test.name) // domesy
achieve modularization
.
方案:
export default Index
export { name as newName }
import Index from './Index'
import * as Index from './Index'
import { name, value, id } from './Index'
import './Index'
import { name as newName } from './Index'
import './Index'
import Index, { name, value, id } from './Index'
export命令
and import命令
are combined into one line. The interface causes the current module to directly use its import variables. It is suitable for all sub -modules to export
Let ARR = [1, 2, 3, 4] // includes () ES6 console.log (Arr.includes (3)) // true console.log ([1, 2, nan] .includes (nan); // true // includes () ES7 console.log (Arr.includes (1, 0)) // true console.log (Arr.includes (1, 1)) // False
**
represents Math.pow()
// Motor transportation calculation ES7 console.log (math.pow (2, 3)) // 8 console.log (2 ** 8) // 256
Let Str = 'Domesy' // padStart (): Will it be supplemented in the form of a space? Here is 0 instead of 0. The second parameter will define a template form. The template will replace the console.log ("1" .padStart (2, "0" )); // 01 console.log ("8-27" .padstart (10, "yyyy-0m-0d"); // yyyy-08-27 // Padend (): The same console.log ("1" .padend (2, "0")); // 10
Let obj = {name: 'domesy', value: 'react'} //Object.values () console.log (object.values (obj)) // ['react', 'react'] //Object.entries () console.log (object.entries (obj)) // [['name', 'value'], ['react', 'react']]
: change the asynchronous function to the synchronous function , (generator's grammar grammar Sugar)
const func = async () => {{ Let promise = new promise (resolve, reject) => { setTimeout(() => { Resolve ("execute"); }, 1000); }); console.log (Await Promise); console.log (Await 0); console.log (Await Promise.Resolve (1)); console.log(2); Return Promise.Resolve (3); } func (). then (val => { console.log (value); // execute in order: execute 0 1 2 3 });
Special attention:
Promise
object, so you can use the then
async/await
of the forEach()
array will be invalidated. You can use for-of
and Promise.all()
instead ofreject
object that cannot be processed by Promise, you need to use try catch
to captureThis is divided into two cases:
if the Promise object is not a promise, AWAIT will block the code behind, first execute the synchronous code outside Async, execute the synchronization code, and then return to the inside of Async. Take this non -Promise as Await as Await The result of the expression.
If it is waiting for a Promise object, Await will also suspend the code behind Async, first execute the synchronous code outside the async, wait for the Promise object Fulfilled, and then use the paranolve parameter as the computing result of the AWAIT expression.
The advantages and:
advantages in terms of advantages:
undefined
, and the original string can be obtained from raw
.// Relax of the restrictions of the string const = (value) => {{ console.log (value) } Test `domesy` // ['domesy', raw: [" domesy "]]
promise.finally ()
letting function, return new Promise((res, rej) => { setTimeout(() => { if (time <500) { Res (time) }else{ Rej (time) } }, time) }) } func (300) .then ((VAL) => Console.log ('Res', Val)) .catch ((erro) => console.log ('rea', erro)) .finally (() => Console.log ('Complete')) // Execute results: Res 300 completes func (700) .then ((VAL) => Console.log ('Res', Val)) .catch ((erro) => console.log ('rea', erro)) .finally (() => Console.log ('Complete')) // Execute results: REJ 700 completes
FOR-AWAIT-OF: Asynchronous iterator, cycle waiting for each Promise对象
to become resolved状态
before entering the next step
gettime = (sex) => {{ Return New Promise (res => {{ setTimeout(() => { Res (Seconds) }, sex) }) } async function test () { let arr = [gettime (2000), gettime (500), gettime (1000)] for await (let x of arr) { console.log (x); } } test () // Perform the 2000 500 1000
//json.stringify () Upgrade console.log (json.stringify (" ud83d ude0e"); console.log (json.stringify (" u {d800}"); // ud800
Infinity
automatically to the bottom))Let ARR = [1, 2, 3, 4] // flash () console.log (Arr.Map ((x) => [x * 2])); // [[2], [4], [8], [8]] console.log (Arr.flatmap ((x) => [x * 2])); // [2, 4, 6, 8] console.log (Arr.flatmap ((x) => [[x * 2]]); // [[2], [4], [6], [8]] const arr1 = [0, 1, 2, [3, 4]]; const arr2 = [0, 1, 2, [[3, 4]]];; console.log (arr1.flat ()); // [0, 1, 2, 3, 4] console.log (Arr2.flat (2)); // [0, 1, 2, [3, 4]]]
(Arr2.Flat (Infinity)); // [0, 1, 2, 3, 4]
Object.entries()
Let Map = New Map ([[[[[[[[[[[[[[[[[[[ [a ", 1], ["b", 2],, ]); let obj = object.fromentries (map); console.log (obj); // {a: 1, b: 2}
// Note that the form of an array is left arr = [ [a ", 1], ["b", 2],, ] let obj = object.fromentries (ARR); console.log (obj); // {a: 1, b: 2}
Let obj = { A: 1, B: 2, C: 3 } let res = object.fromentries ( Object.entries (obj). Filter ([[key, value]) => value! == 3) ) console.log (res) // {a: 1, b: 2}
// tostring () function test () { consical.log ('domesy') } console.log (test.tostring ()); // function test () { // consume.log ('domesy') //}
are in ES10, Try Catch can ignore the parameter
let func = (name) => { try { Return json.parse (name) } catch { return false } } console.log (func (1)) // 1 console.log (func ({a: '1'})) // False
.
// Number console.log (2 ** 53) // 9007199254740992 console.log (number.max_safe_integer) // 9007199254740991 // bigint const bigint = 9007199254740993n console.log (bigint) // 9007199254740993n console.log (Typeof Bigint) // Bigint console.log (1N == 1) // true console.log (1N === 1) // false const Bigintnum = Bigint (9007199254740993N) console.log (bigintnum) // 9007199254740993nThere are 7
in ES6, namely: srting
, number
, boolean
, object
, null
, undefined
, symbol
object
includes: Array
, Function
, Date
, RegExp
and newly added one of the 8th. They are: srting
, number
, boolean
, object
, null
, undefined
, symbol
, BigInt
Promise.allSettled ():
Promise.all()
promise.allSetky ([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[) Promise.reject ({{ CODE: 500, MSG: "Services", }), Promise.Resolve ({{ code: 200, data: [1 "," 2 "," 3 "], }), Promise.Resolve ({{ code: 200, data: [4 "," 5 "," 6 "], }), ])). ((res) => {{{ console.log (res) // [{reason: {code: 500, msg: 'service abnormality'}, status: "rejected"}, // {reASON: {code: 200, data: [1 "," 2 "," 3 "]}, status:" rejected "}, // {reASON: {code: 200, data: [4 "," 5 "," 6 "]}, status:" rejected "}] const data = res.filter ((item) => item.status === "fulfilled"); console.log (data); // [{reASON: {code: 200, data: [1 "," 2 "," 3 "]}, status:" rejected "}, // {reASON: {code: 200, data: [4 "," 5 "," 6 "]}, status:" rejected "}] })
require
: require()
is a synchronous loading , import()
is asynchronous loading// then (then () let modulePage = "index.js"; Import (modulePage) .then ((module) => {{ module.init (); }); // Combined with Async Await (async () => { const modelpage = 'index.js' const module = await import (modulePage); console.log (module) })
// browser environment console.log (globalthis) // window // node Console.log (globalthis) // Global
Const user = {name: 'domesy'} // ES11 before Let A = User && User.name // Now let b = user? .Name
"||" default value "; // default value "" ?? "Default Value"; // "" " const b = 0; const a = b || 5; console.log (a); // 5 const b = null // undefined const a = b ?? 123; console.log (a); // 123
expans () replace ()
the Let Str = "Hi!, This is the new feature of ES6 ~ ES12, which is currently ES12" console.log (str.replace ("ES", "SY"); // Hi! , This is the new feature of SY6 ~ ES12. It is currently ES12 console.log (str.replace (/es/g, "sy"); // hi! , This is the new feature of SY6 ~ SY12. It is currently SY12 console.log (str.replaceall ("es", "sy"); // hi! , This is the new feature of SY6 ~ SY12. It is currently SY12 console.log (str.replaceall (/es/g, "" sy "); // hi!This is the new feature of SY6 ~ SY12.
SY12
Promise.any ()
.Promise.any ([[[[[[[[[[[[[[[[[[[[[[[[[[[[ Promise.reject ("Third"), Promise.Resolve ("Second"), Promise.Resolve ("first"), ]) .then ((res) => console.log (res) // second .catch ((ERR) => Console.error (ERR)); Promise.any ([[[[[[[[[[[[[[[[[[[[[[[[[[[[ Promise.reject ("Error 1"), Promise.reject ("ERROR 2"), Promise.reject ("Error 3"), ]) .then ((res) => console.log (res)) .catch ((ERR) => Console.error (ERR)); // aggregateerror: all promises we rejected Promise.any ([[[[[[[[[[[[[[[[[[[[[[[[[[[[ Promise.Resolve ("Third"), Promise.Resolve ("Second"), Promise.Resolve ("first"), ]) .then ((res) => console.log (res) // Third .catch ((ERR) => Console.error (ERR));
Let Weakref = New Weakref ({name: 'domesy', year: 24}) weakref.Deref () // {name: 'domesy', year: 24} weakref.Deref (). Year // 24
let num1 = 5; let num2 = 10; num1 && = num2; console.log (num1); // 10 // equivalent at Num1 && (NUM1 = NUM2); if (num1) {{ num1 = num2; }
Let Num1; let num2 = 10; num1 || = num2; console.log (num1); // 10 // equivalent at num1 || (num1 = num2); if (! num1) { num1 = num2; }
. let num2 = 10; let num3 = null; // undefined num1 ?? = num2; console.log (num1); // 10 num1 = false; num1 ?? = num2; console.log (num1); // false num3 ?? = 123; console.log (num3); // 123 // equivalent at // num1 ?? (num1 = num2);
let num1 = 100000; Let Num2 = 100_000; console.log (num1); // 100000 console.log (num2); // 100000 const num3 = 10.12_34_56 console.log (num3); // 10.123456