I’m participating in nuggets Creators Camp # 4, click here to learn more and learn together!
Hello, everyone, I am small dudu, is a love to start to knock on the code of the little rookie, I think the code should personally knock again, in order to better remember in mind, so today I will introduce about ES6 ~ ES12 features. If you have a blind spot with ES, or are not familiar with the new features, this article should help you
In order to better understand, we use the case model to explain, so that a better understanding, at the same time, the case column also supports the developer mode of debugging, we hope you can support more ~
ECMAScript
ECMAScript is a scripting language standardized by Ecma International (formerly the European Computer Manufacturers Association) through ECMA-262. It’s also a standard for JavaScript
In the world of programmers, there are only two versions: ES5 and ES6. ES6 was released in 2015, which is the official beginning of the big front end era. That is to say, it is called ES5 before 2015, and ES6 after 2016
For ES6 features, please see Introduction to ES6 Standards by Ruan Yifeng.
ES6
The statement
let & const
Recommendation: ⭐ ️ ⭐ ️
The difference between let, const, and var:
- Variables declared by var are promoted, while let and const are not. Variable promotion: Whether a variable can be called in the declaration money
- Var has no block-level scope, let and const have block-level scope
- Let and const are not allowed to be declared twice in the same scope. Const is a read-only variable and must be assigned
In addition, when const declares an object, the properties of the object can be changed, because const obj only holds the reference address of the object. As long as the address is unchanged, nothing goes wrong
Deconstruction assignment
Array deconstruction
- In order
- You can take a value out of an array, assign a value to a variable, and that’s pattern matching
- You can use
.
Deconstruct and represent the rest - If the original array does not exist, the default value can be set on the corresponding value; otherwise, it is
undefined
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
Copy the code
Object structure
- An unordered line that requires only the same name of the variable as the attribute name
- If the attribute names of the variable and object do not duplicate, the value of the variable is
undefined
- Pay attention to
:
He is equivalent to an alias
let { 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); // There is no a variable
console.log(b); / / 1
Copy the code
Deconstruction of strings
- Strings can also be deconstructed, which translates into array-like objects
- Comes with a
length
Attribute, representing number
let [a, b, c, d, e] = "hello"
console.log(a, b, c, d, e) // h e l l o
let { length } = "hello"
console.log(length) / / 5
Copy the code
Deconstruction of numbers and Boolean values
- Any undead object or array that is deconstructed is converted to an object first, so numeric and Boolean types are also converted to objects
let { toString: s } = 123;
console.log(s === Number.prototype.toString) // true
let { toString: s } = true;
console.log(s === Boolean.prototype.toString) // true
Copy the code
The deconstruction of functions
- Functions can also have a deconstruction, that is, the return value of the deconstruction
function test({x = 0, y = 0}) {
return [x, y]
}
let [a, b] = test({x = 1, y = 3})
console.log(a, b) / / 1 and 3
let [a, b] = test({x = 0, y = 0})
console.log(a, b) / / 0, 0
Copy the code
Regular extension
Re is actually a very difficult knowledge point, if someone can fully grasp, it is really very powerful, here is a simple say
First, there are two styles: JS and Perl
JS subdivision: RegExp()
let re = new RegExp('a'); A let re = new RegExp('a', 'I '); // The first is the object to look for, and the second is the optionCopy the code
Perl style: / rules/options, and can follow multiple, in no order
let re = /a/; A let re = /a/ I; // The first is the object to look for, and the second is the optionCopy the code
Here is a regular expression online test (with a common regular expression) : regular expression online test
String extension
- Unicode:
Curly braces contain
Represents Unicode characters - CodePointAt (): Returns the character corresponding code point corresponding to fromCharCode()
- String.fromcharcode (): Returns the corresponding codepoint as a character, corresponding to codePointAt()
- String.raw() : Returns the result of replacing all the variables of the String and escaping the slash
- StartsWith (): Returns a Boolean value indicating whether the argument string is at the head of the original string.
- EndsWith () : Returns a Boolean value indicating whether the argument string is at the end of the original string.
- Repeat () : method returns a new string, indicating that the original string is repeated n times
- Traversal: the for –
- Includes () : Returns a Boolean value indicating whether the parameter string was found.
- TrimStart () : method removes whitespace from the beginning of the string. TrimLeft () is an alias for this method.
- TrimEnd () : method removes whitespace characters from the end of a string. TrimRight () is an alias for this method.
//Unicode
console.log("a"."\u0061"); // a a
console.log("d"."\u{4E25}"); / / d
let str = 'Domesy'
//codePointAt()
console.log(str.codePointAt(0)) / / 68
//String.fromCharCode()
console.log(String.fromCharCode(68)) // D
//String.raw()
console.log(String.raw`Hi\nThe ${1 + 2}`); // Hi\n3
console.log(`Hi\nThe ${1 + 2}`); 3 / / Hi
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 argument is automatically rounded up or converted to a number if it is a string
console.log(str.repeat(2)) // DomesyDomesy
console.log(str.repeat(2.9)) // DomesyDomesy
// traversal: for-of
for(let code of str){
console.log(code) D o m e s y
}
//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!"
Copy the code
other
String templates can be inserted single-line or multi-line, using ‘
let str = `Dome sy`
console.log(str) // Will wrap automatically
// Dome
// sy
Copy the code
Label template:
const str = {
name: 'Little Dudu'.info: 'hello,'} the console. The log (` ${STR. Info}, I am a ` ${STR. Name} `) / / hello, everyone, I am komori duCopy the code
Array extension
- Array.of(): Converts a set of values to an Array, returning a new Array regardless of the number or type of arguments.
- CopyWithin () : Copies the member from the specified location to another location, returning the original array
- Find (): Returns the first value that matches the condition
- FindIndex () : Returns the first index that matches the criteria
- Keys () : traversal of the key name, returns an traverser object, which can be used as a for-of loop,
- Values () : Same as keys(), but traversal of key values
- Entries () : Same as keys(), but traversal of key-value pairs
- Array.from(): Creates a new Array instance from an array-like or iterable.
- Fill (): Fills the array with specified elements and returns the original array
- Includes () : determines whether an element is included, returns a Boolean value, also available for NaN, but does not locate
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: indicates the location of the target
// start: the start position, which can be omitted or negative.
// end: the end position, can be omitted, can be negative, 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
}
// values()
for (let index of arr.values()) {
console.log(index); // Return 1, 2, 3, 4, 5
}
// entries()
for (let index of arr.entries()) {
console.log(index); // Return [0, 1] [1, 2] [2, 3] [3, 4] [4, 5]
}
let arr = [1.2.3.4.5]
// array.from (): traversal can be pseudo-arrays, such as String, Set, Node
let arr1 = Array.from([1.3.5].(item) = > {
return item * 2;
})
console.log(arr1) / / [2, 6, 10]
// Fill (): three arguments (target, start = 0, end = this.length)
// target: indicates the location of the target
// start: the start position, which can be omitted or negative.
// end: the end position, can be omitted, can be negative, 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
Copy the code
other
Extension operators:…
// It expands an array
let arr = [3.4.5]
console.log(... arr)/ / 3, 4, 5
let arr1 = [1.2. arr]console.log(... arr)// 1, 2, 3, 4, 5
Copy the code
Object extension
- Object.getprototypeof () : Returns the prototype Object of the Object
- Object.setprototypeof () : Sets the prototype Object of the Object
- Proto: The prototype object that returns or sets the object
- Object. GetOwnPropertyNames () : returns an array of Object itself a key Symbol attribute of
- Object. GetOwnPropertySymbols () : returns an array of Object itself a key Symbol attribute of
- Reflect.ownkeys (): Returns an array of all the property keys of the object itself
- Object.is() : Checks whether two objects are equal, the array points to different addresses, so any array comparison must be false
- Through:
for-in
- Object.keys() : Returns the property name
- Object.assign() : Used to copy the values of all enumerable attributes from one or more source objects to the target Object, returning the target Object, which also changes
//Object.is()
console.log(Object.is('abc'.'abc')) // true
console.log(Object.is([], [])) // false
// traversal: for-in
let obj = { name: 'Domesy'.value: 'React' }
for(let key in obj){
console.log(key); // Return the attribute value name value
console.log(obj[key]); // Return the property value of 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}
Copy the code
other
Concise notation
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
Copy the code
Attribute expressions: Use variables or expressions directly to define the key of an Object
let a = "b"
let obj = {
[a]: "c"
}
console.log(obj) // {b : "c"}
Copy the code
Extended operators…
- Many additional features have been added in ES9, such as merging, escaping strings, and so on
// It expands an array
let{ a, b, ... c } = {a: 1.b: 2.c: 3.d: 4};
console.log(c) // {c: 3, d: 4}
letObj1 = {c:3 }
let obj = { a: 1.b: 2. c}console.log(obj) // { a: 1, b: 2, c: 3}
Copy the code
Numerical extension
- binary:
0b
或0B
The beginning represents binary - octal:
00
或0O
The beginning represents binary - Number.isfinite (): used to check whether a Number isFinite, returning a Boolean value
- Number.isnan (): Checks if a value is a NaN and returns a Boolean value
- Number.isinteger (): Checks whether a value is an integer and returns a Boolean value
- Number.issafeinteger (): Checks whether a value is a safe integer and returns a Boolean value
- Math.cbrt(): Returns the cube
- Math.abrt() : Returns the cube
- Math.cbrt(): Returns the cube
- Math.clz32(): Returns the 32-bit unsigned integer form of the number
- Math.imul(): Returns the multiplication of two values
- Math.fround(): Returns the 32-bit single-precision floating-point form of a numeric value
- Math.hypot(): Returns the square root of the sum of squares of all values
- Math.expm1(): Returns e^n – 1
- Math.log1p(): Returns the natural logarithm of 1 + n (math.log (1 + n))
- Math.log10(): Returns the logarithm base 10 of n
- Math.log2(): Returns the logarithm base 2 of n
- Math.trunc(): Removes the decimal part of a number and keeps only the integer part
- Math.sign(): Returns a numeric type
A positive number is 1
,A negative number to 1
,Zero is zero
,Negative zero - 0
,NaN
- Math.abrt(): Returns the cube root
- Math.sinh(): Returns hyperbolic sine
- Math.cosh(): Returns the hyperbolic cosine
- Math.tanh(): Returns the hyperbolic tangent
- Math.asinh(): Returns inverse hyperbolic sine
- Math.acosh(): Returns the inverse hyperbolic cosine
- Math.atanh(): Returns the inverse hyperbolic tangent
- Number.parseInt(): The integer part of the return value
parseInt
- Number.parseFloat(): returns the part worth floating point, equivalent to
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
Copy the code
Function extension
- Function argument trailing comma: Allows function last argument to have trailing comma
- The parameter defaults to a specific value
// The argument defaults to a specific value
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
fun(1); 1 / / 2, 1
Copy the code
other
Rest arguments (extended operators…)
function fun(. arg){
console.log(arg) // [1, 2, 3, 4]
}
fun(1.2.3.4)
Copy the code
Arrow function
- Define the function as =>
let arrow = (v) = > v + 2
console.log(arrow(1)) / / 3
Copy the code
The difference between arrow functions and ordinary functions
- Arrow functions are different from normal functions. The syntax of arrow functions is more concise and clear. Arrow functions are => define functions, while normal functions are function define functions.
- A Set has no keys and only values, so you can think of both keys and values as the same
- Arrow functions do not actually have this; this in arrow functions depends only on the this of the first normal function that wraps the arrow function.
- Arrow functions have no arguments of their own. Calling Arguments in the arrow function actually gets the value in the outer local (function) execution environment.
- Call, apply, and bind do not affect the direction of this.
- Arrow function this points to the context, normal function this does not point to the context, bind(this) if necessary
Set
Set is a new data structure in ES6. It is similar to an array, but the values of its members are unique and there are no duplicate values
Const set = new set ()
Properties:
- Size: Returns the number of values in the Set object
Methods:
- Add (): Adds an element to the end of a Set. Returns the Set object
- Delete (): Removes elements in a Set that are equal to this value, returning true if there is one or false if there is none
- Clear (): Clear all elements of Set
- Has (): Whether the value exists, true if it does, false otherwise
- Keys () : objects traversed by attribute values
- Values () : Objects traversed by attribute values
- Entries () : Objects traversed by property values and property values
- ForEach () : Iterate over each element
Special attention:
- Of the traverser
iterator
Object, in insertion order, of the form [Key, Value] - Values added to a Set are not cast, so 1 and “1” are two different values
- Inside a Set, it is determined by ===, that is, two objects can never be the same because their addresses are different
- The only difference is NaN
let list = new Set(a)//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); {id: 1} {id: 2} {id: 3}
}
//values()
for (let key of list.values()) {
console.log(key); {id: 1} {id: 2} {id: 3}
}
//entries()
for (let data of list.entries()) {
console.log(data); / / to print: [{id: 1}, {1} id:] [id: 2}, {2} id:] [id: 3}, {3} id:]
}
//forEach
list.forEach((item) = > {
console.log(item){id: 1} {id: 2} {id: 3}
});
Copy the code
Application:
Array to heavy
- One thing to note
new Set
Unable to 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']
Copy the code
Union, intersection and difference can be found
let a = new Set([1.2.3])
let b = new Set([2.3.4])
/ / and set
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}
Copy the code
Map collections
let set = new Set([1.2.3])
console.log(new Set([...set].map(v= > v * 2))) // Set(3) {2, 4, 6}
Copy the code
WeakSet
Definition: and Set structures, but the member values can only be objects
Const set = new WeakSet() const set = new WeakSet()
Methods:
- Add (): Adds an element to the tail of a WeakSet object. Return the instance
- Delete (): Remove the element equal to the value in WeakSet,
- Has (): Whether the value exists, true if it does, false otherwise
Note:
- WeakSet member objects are weak references, that is, garbage collection mechanism does not consider the application of the object. Simply put, WebSet objects cannot be traversed
- The advantage is that there is no memory leak when the instance is deleted again
Map
Recommended index: ⭐️⭐️
A Map, a new data structure in ES6, is like an object whose member keys are values of any type
Const set = new Map()
Properties:
- Constructor: Returns Map
- Size: Returns the number of values in the Map instance
Methods:
- Set (): a key-value pair after the Map is added, returning the instance
- Get (): Returns a key-value pair
- Delete (): Removes elements in the Map that are equal to this value, returning true if there is one or false if there is none
- Clear (): Clears all elements of the Map
- Has (): Whether the value exists, true if it does, false otherwise
- Keys () : Objects traversed by property keys
- Values () : Objects traversed by attribute values
- Entries () : Object traversed by property keys and property values
- ForEach () : Iterate over each element
Special attention:
- A reference to the same object is treated as a key
- The same key, it’s overwritten
let map = new Set(a)//set()
map.set('a'.1)
map.set('b'.2)
console(map) // Map(2) {'a' => 1, 'b' => 2}
//get
map.get("a") / / 1
//size
console(map.size) / / 2
//delete()
map.delete("a") // true
console(map) // Map(1) {'b' => 2}
//has()
map.has('b') // true
map.has(1) // false
//clear()
map.clear()
console(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: a, b, c
}
//values()
for (let value of map.values()) {
console.log(value); // Print: 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: 1, 2, 3
});
Copy the code
WeakMap
Definition: and Map structure, but the member values can only be objects
Const set = new WeakMap() const set = new WeakMap()
Methods:
- Set (): Adds a key-value pair and returns an instance
- Get (): Returns a key-value pair
- Delete (): deletes key-value pairs, true if they exist, false otherwise
- Has (): Whether the value exists, true if it does, false otherwise
Symbol (original type)
Symbol is a primitive data type introduced in ES6 that stands for unique
Const sy = Stmbol()
Parameter: string(Optional)
Methods:
- Symbol.for(): Creates a parameter description
Symbol value
If this parameter exists, return the originalSymbol value
(Search before create, register in global environment) - Symbol.keyFor(): Returns the registered
Symbol value
Can only be returnedSymbol.for()
thekey
) - Object.getOwnPropertySymbols(): returns all names used as attribute names in the object
Symbol value
An array of
/ / declare
let a = Symbol(a);let b = Symbol(a);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
Copy the code
Proxy
Proxy is used to modify the default behavior of certain operations, which is equivalent to making changes at the language level. Therefore, it is a kind of “meta programming”, that is, programming a programming language
A Proxy is a layer of interception set in front of the target object. All external access must go through this layer of interception, so it provides a mechanism for filtering and rewriting external access.
Proxy here can be understood as Proxy
Const proxy = new proxy (target, handler)
- Target: intercepts the object
- Handler: Defines the method to intercept
Methods:
- Get (): Intercepts reading of object properties
- Set (): Intercepts the object setting property, returning a Boolean value
- Has (): Intercepts the propKey in proxy operation, returning a Boolean value
- OwnKeys (): Intercepts object property traversal and returns an array
- DeleteProperty () : Intercepts the delete proxy[propKey] operation and returns a Boolean ()
- Apply () : Intercepts function calls, call and apply operations
- Construct () : intercepts the new command and returns an object
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 {
returntarget[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 {
returntarget[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 from the ()
console.log("name" in data) // true
console.log("time" in data) // false
/ / delete deleteProperty ()
delete monitor.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) {
returntarget(... 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 newtarget(... args); }});console.log(new User("domesy")); // User {name: 'domesy'}
Copy the code
Reflect
Reflect is similar to Proxy, but retains the default behavior of Object
- Put some methods of Object that are clearly internal to the language (such as Object.defineProperty) on Reflect.
- At this stage, some methods are deployed on both Object and Reflect objects, and future new methods will only be deployed on Reflect objects
- Modify the return results of some Object methods to make them more reasonable. For example, Object.defineProperty(obj, name, desc) throws an error if the attribute cannot be defined, while Reflect.defineProperty(obj, name, desc) returns false
- Make the Object operation function behavior
Reflect’s method corresponds to Proxy’s, which I won’t cover here
Class
Class: An abstraction of a Class of things that have common characteristics (constructor syntax sugar)
Constructor () basic definition and generation of instances
class Parent {
constructor(name = 'es6'){
this.name = name
}
}
let data = new Parent('domesy')
console.log(data) // Parent { name: 'domesy'}
Copy the code
Extends inheritance
class Parent {
constructor(name = 'es6'){
this.name = name
}
}
// Common 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'}
Copy the code
getter setter
- These two methods are important and are often used to encapsulate apis
- Get and set are properties, not 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
Copy the code
Static static method
- Static methods, which cannot be called on an instance of a class, should be called from the class itself
class Parent {
static getName = (name) = > {
return ` hello!${name}`}}console.log(Parent.getName('domesy')) / / hello! domesy
Copy the code
Static attributes
class Parent {}
Parent.type = "test";
console.log(Parent.type); //test
Copy the code
Promise
Promise was designed to solve the problem of “callback hell” by making the handling of asynchronous operations elegant.
Promises can support multiple concurrent requests, and retrieve data from concurrent requests. This Promise solves the problem of asynchrony
Definition: An object that contains the result of an asynchronous operation
Status:
- Pending: Indicates the initial state
- This is a big pity
- The operation fails
Note:
- The Promise determines which method to execute based on the state
- The default state of Promise instantiation is pending, such as asynchronous state exception Rejected, and the reverse is fulfilled
- The state transformation is one-way and irreversible. The determined state (depressing/Rejected) cannot be reversed back to the initial state (pending), and it can only be from pending to depressing or Rejected
Basic usage
// Common definition
let ajax = (callback) = > {
console.log('material')
setTimeout(() = > {
callback && callback.call();
}, 1000)
}
ajax(() = > {
console.log('timeout')})// Start execution with a timeout after 1s
//Promise
let ajax = () = > {
console.log("Commence execution");
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve();
}, 1000);
});
};
ajax().then(() = > {
console.log("timeout");
});
// Start execution with a timeout after 1s
// then()
let ajax = () = > {
console.log("Commence execution");
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve();
}, 1000);
});
};
ajax()
.then(() = > {
return new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve();
}, 2000);
});
})
.then(() = > {
console.log("timeout")})3s(1+2) and then timeout
// catch()
let ajax = (num) = > {
console.log("Commence execution");
return new Promise((resolve, reject) = > {
if (num > 5) {
resolve();
} else {
throw new Error("Something went wrong."); }}); }; ajax(6)
.then(function () {
console.log("timeout"); // Start execution with a timeout after 1s
})
.catch(function (err) {
console.log("catch", err);
});
ajax(3)
.then(function () {
console.log("timeout");
})
.catch(function (err) {
console.log("catch"); // A catch is played 1s later
});
Copy the code
Promise.all() batch operation
- Promise.all(arR) is used to wrap multiple Promise instances into a new Promise instance, and the returned instance is a regular Promise
- It takes an array as an argument
- The array can be a Promise object, it can be anything else, and only the Promise will wait for the state to change
- When all the child promises are complete, the Promise is complete, and the return value is an array of all values
- If either Promise fails, the return value is the result of the first failed child Promise
// Add all images to the page after loading
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);
Copy the code
Promise.race()
- A race is similar to an All, except that it executes as soon as one is finished
// One is loaded back to the page after 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);
Copy the code
The problem of Promise
- Once executed, there is no way to cancel it in the middle
- Errors cannot be caught externally, but can only be anticipated internally. If no callback function is set, errors thrown internally by a Promise will not be reflected externally
- How promises are executed internally can be difficult to monitor, and when in a pending state, there is no way to tell what stage of progress is currently being made (just started or close to completion)
Generator
Generator: A function that can be used to control iterators and an asynchronous programming solution that encapsulates multiple internal states. Also called a Generator function
Parameters that
- Yield toA “pause” to control execution within a programAnd returns an object containing two attributes:
value
和done
- Among them
value
On behalf of the value,done
Return Boolean (if false, subsequent, true completed) - Next to
restore
Program execution - Generator functions cannot be defined using arrow functions, otherwise SyntaxError will be raised
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}
Copy the code
The Iterator traverses
Iterator is an interface that provides a unified access mechanism for various data structures. The Iterator interface can be deployed on any data structure to complete traversal (that is, processing all members of the data structure in turn).
Iterator does:
- One is to provide a unified and simple access interface for all kinds of data structures
- Allows the members of a data structure to be arranged in some order
- ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption
- For-in traversal order: Have different engines agreed on how to iterate over attributes to standardize behavior ES11
Note:
- In ES6, some data structures have a native Iterator interface (such as arrays) that can be used for… Of loops over, some don’t (like objects)
- In ES6, there are three types of data structures that have Iterator interfaces natively:
An array of
,Some array-like object
,Set
andStructure of the Map
. - An example of adding an Iterator interface to an object.
// Basic usage
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, done: true}
// for of loop
let arr = ["hello"."world"];
for (let value of arr) {
console.log(value); // hello world
}
// Object processing
let obj = {
start: [1.5.2].end: [7.9.6],
[Symbol.iterator](){
let index = 0;
let arr = this.start.concat(this.end)
return {
next(){
if(index < 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 9 6
}
Copy the code
The Decorator Decorator
- use
@
Symbol used to extend and modify the behavior of a class - Third-party libraries need to be introduced when using:
core-decorators
const name = (target) = > {
target.name = "domesy"
}
@name
class Test{}
console.log(Test.name) //domesy
Copy the code
modular
In the early days, it was common to implement modularity using immediately executing functions, which solved naming conflicts and contaminated global scopes through function scopes
Benefits of using modularity:
- Resolving naming Conflicts
- Provide reusability
- Improve code maintainability
Solution:
- CommonJS: For servers (dynamic dependencies)
- AMD: for browsers (dynamic dependencies, rarely used)
- CMD: for browsers (dynamic dependencies, rarely used)
- UMD: For browsers and servers (dynamic dependencies)
- ESM: For browsers and servers (static dependencies)
Export export module
- Default export:
export default Index
- ‘export const name = ‘domesy’
- Export on demand (recommended) : ‘export {name, value, id}’
- Rename export:
export { name as newName }
Import Import module
- Default import (recommended) :
import Index from './Index'
- Overall import:
import * as Index from './Index'
- Import on demand (recommended) :
import { name, value, id } from './Index'
- Rename import:
import { name as newName } from './Index'
- Directed by:
import './Index'
- Conforming to import (recommended) :
import Index, { name, value, id } from './Index'
Composite patterns
The export command and import command are combined in one line. The variables are not imported into the current module, which is equivalent to the external forwarding interface. As a result, the current module cannot directly use its imported variables
- Default import/export: ‘export {default} from ‘./Index’
- Export * from ‘./Index’
- Import/export as required: ‘export {name, value, ID} from ‘./Index’
- Export {default as name} from ‘./Index’
ES7
Array extension
- Includes (): An index is added to ES6 to represent where to find ES7
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
Copy the code
Numerical extension
- Power operator:
**
On behalf ofMath.pow()
// The power operator ES7
console.log(Math.pow(2.3)) / / 8
console.log(2 ** 8) / / 8
Copy the code
ES8
Character transmission extension
- PadStart () : used for head completion
- PadEnd () : used for tail completion.
let str = 'Domesy'
//padStart(): will it be filled with Spaces, instead of 0, and the second argument will define a template form, which will be replaced with a template
console.log("1".padStart(2."0")); / / 01
console.log("8-27".padStart(10."YYYY-0M-0D")); // YYYY-08-27
// padEnd() : same as padStart()
console.log("1".padEnd(2."0")); / / 10
Copy the code
Object extension
- Object.values() : Returns the attribute value
- Object.entries() : Returns an array of property names and property values
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']]
Copy the code
async await
Effect: Change an asynchronous function to a synchronous function, (Generator syntax)
const func = async() = > {let promise = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve("Performing");
}, 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(val); // Perform 0, 1, 2, and 3 in sequence
});
Copy the code
Special attention:
- Async function returns
Promise
Object, and therefore can be usedthen
- The awit command can only be used in async functions, otherwise an error will be reported
- An array of
forEach()
performasync/await
It will fail. It can be usedfor-of
和Promise.all()
Instead of - Unable to process a promise return
reject
Object that needs to be usedtry catch
To capture the
What did Awiait do when it arrived?
There are two cases: whether it’s a promise object
If it is not a promise, await blocks the following code, executes the synchronous code outside async, executes the synchronous code, and then goes back inside async, treating the non-promise as the result of an await expression.
This will be a pity. Then, the resolve parameter will be used as the result of the await expression.
Advantages and disadvantages of async await versus promise
Advantages:
- It achieves true serial synchronous writing, the code is relatively easy to read
- For conditional statements and other process statements are more friendly, can be directly written to the judgment condition inside
- Advantages in code clarity when dealing with complex processes
Disadvantages:
- Using await can cause performance problems because await blocks code, perhaps subsequent asynchronous code does not depend on the former but still needs to wait for the former to complete, causing the code to lose concurrency.
ES9
Character transmission extension
- Relax restrictions on escaping strings in tag templates: An invalid string escape was encountered
undefined
And from theraw
The original string is available on.
// Relax strings
const test = (value) = > {
console.log(value)
}
test `domesy` // ['domesy', raw: ["domesy"]]
Copy the code
Promise
Promise.finally()
- A callback that executes regardless of its final state
let func = time= > {
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('rej', erro))
.finally(() = > console.log('complete'))
// Result: res 300 completed
func(700)
.then((val) = > console.log('res', val))
.catch((erro) = > console.log('rej', erro))
.finally(() = > console.log('complete'))
// Rej 700 completed
Copy the code
for-await-of
For-await-of: Asynchronous iterator that loops until each Promise object becomes resolved before moving to the next step
let getTime = (seconds) = > {
return new Promise(res= > {
setTimeout(() = > {
res(seconds)
}, seconds)
})
}
async function test(){
let arr = [getTime(2000),getTime(500),getTime(1000)]
for await (let x of arr){
console.log(x);
}
}
test() // Execute 2000 500 1000
Copy the code
ES10
Character transmission extension
- Json.stringify (): Returns a string that does not conform to the UTF-8 standard (U+2028 and U+2029 are available)
/ / JSON. Stringify () to upgrade
console.log(JSON.stringify("\uD83D\uDE0E")); / / 😎
console.log(JSON.stringify("\u{D800}")); // \ud800
Copy the code
Array extension
- FlatMap (): The method first maps each element using a mapping function and then compresses the result into a new array. (Note: This is almost identical to a flat with a depth value of 1 attached to a map, but flatmaps are usually slightly more efficient when combined into one method.)
- flatThe: method iterates through the array recursively at a specified depth and returns a new array with all the elements in the traversed subarray. Default is 1.(Application:Array flattening(when the input
Infinity
Automatic solution to the bottom))
let arr = [1.2.3.4]
// flatMap()
console.log(arr.map((x) = > [x * 2])); [[2], [4], [6], [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]]
console.log(arr2.flat(Infinity)); // [0, 1, 2, 3, 4]
Copy the code
Object extension
Object.fromEntries()
- Returns an object consisting of keys and values equivalent to
Object.entries()
The inverse operation - You can do some data type conversions
Map is converted to Object
let map = new Map([["a".1],
["b".2]]);let obj = Object.fromEntries(map);
console.log(obj); // {a: 1, b: 2}
Copy the code
Array is converted to Object
// Note the form of the array
let arr = [
["a".1],
["b".2]]let obj = Object.fromEntries(arr);
console.log(obj); // {a: 1, b: 2}
Copy the code
Object conversion
let obj = {
a: 1.b: 2.c: 3
}
let res = Object.fromEntries(
Object.entries(obj).filter(([key, val]) = >value ! = =3))console.log(res) //{a: 1, b: 2}
Copy the code
Numerical extension
- ToString () : returns the original code of the function (same as the encoding)
//toString()
function test () {
consople.log('domesy')}console.log(test.toString());
// function test () {
// consople.log('domesy')
/ /}
Copy the code
An optional Catch parameter
In ES10, try catch ignores catch parameters
let func = (name) = > {
try {
return JSON.parse(name)
} catch {
return false}}console.log(func(1)) / / 1
console.log(func({a: '1'})) // false
Copy the code
ES11
BigInt(primitive type)
- New primitive data type: BigInt, which represents an integer of arbitrary precision, can represent extremely long data, which can exceed 2 to the power of 53
- The js Number type can only safely represent values from -(2^53-1) to 2^53-1
Special attention:
- The precision of the Number type is limited to 53 binary digits (equivalent to 16 decimal digits, plus or minus 9007199254740992).
- Bigint has no limit on the number of digits, and any integer number of digits can be represented exactly. However, it can only be used as an integer, and to distinguish BigInt from Number, data must be suffixed with n.
- BigInt can use a minus sign, but not a plus sign
- Numbers of type number and Bigint cannot be mixed
// 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) // 9007199254740993n
Copy the code
Basic data types
Srting, Number, Boolean, object, NULL, undefined, symbol
Object includes Array, Function, Date, and RegExp
Srting, Number, Boolean, object, NULL, undefined, symbol, BigInt
Promise
Promise.allSettled():
- Wrap multiple instances into a new instance, return the state array of all instances after the state changes (return after all changes)
- No matter the result is a pity or rejected, there is no need to catch
- It’s kind of enhanced
Promise.all()
Promise.allSettled([
Promise.reject({
code: 500.msg: "Abnormal service",}).Promise.resolve({
code: 200.data: ["1"."2"."3"],}).Promise.resolve({
code: 200.data: ["4"."5"."6"],
}),
]).then((res) = >{
console.log(res) // [{reason: {code: 500, MSG: 'rejected '}, 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" }]
})
Copy the code
Import (): dynamic import
- The on-demand dynamic import. Function format of this class (not inheriting function. prototype) returns the Promise Function
- with
require
The difference between:require()
isSynchronous loading.import()
isAsynchronous loading
// then() let modulePage = "index.js"; import(modulePage).then((module) => { module.init(); }); // incorporate async await (async () => {const modulePage = 'index.js' const module = await import(modulePage); console.log(module) })Copy the code
globalThis
- Global this, regardless of the environment (browser, Node, etc.), always points to the global object
// Browser environment
console.log(globalThis) // window
// node
console.log(globalThis) // global
Copy the code
Optional chain
- Symbol? Does the representative exist
- TypeScript does this in version 3.7
const user = { name: 'domesy' }
/ / ES11 before
let a = user && user.name
/ / now,
letb = user? .nameCopy the code
Null-value merge operator
- A convenient operator for handling default values
- Compared with the | |, null values merge operator?? Only works if the value on the left is strictly null or undefined.
"" || "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
Copy the code
ES12
Character transmission extension
replaceAll()
- The replace() method replaces only the first instance of a pattern in a string
- ReplaceAll () returns a new string that replaces all parts of the original string that match a pattern with a replacement.
- A pattern can be a string or a regular expression, and a replacement can be a string or a function applied to each match.
- ReplaceAll () enhances replace() with full replacement
let str = "Hi! This is a new feature for ES6 to ES12, currently ES12"
console.log(str.replace("ES"."SY")); / / Hi! This is a new feature of SY6 to ES12, currently ES12
console.log(str.replace(/ES/g."Sy")); / / Hi! , this is a new feature of Sy6 to Sy12, currently Sy12
console.log(str.replaceAll("ES"."Sy")); / / Hi! , this is a new feature of Sy6 to Sy12, currently Sy12
console.log(str.replaceAll(/ES/g."Sy")); / / Hi! , this is a new feature of Sy6 to Sy12, currently Sy12
Copy the code
Promise
Promise.any()
- It differs from promise.race () in that, although a Promise’s reject precedes another Promise’s resolve, promise.any () returns the Promise that first resolves.
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 were rejected
Promise.any([
Promise.resolve("Third"),
Promise.resolve("Second"),
Promise.resolve("First"),
])
.then((res) = > console.log(res)) // Third
.catch((err) = > console.error(err));
Copy the code
WeakRefs
- Allows the creation of weak references to objects. This allows you to trace existing objects without preventing them from being garbage collected. Useful for caching and object mapping
- A new WeakRef must be created with the new keyword
- Deref () reads the referenced object
- Proper use of WeakRef objects requires careful consideration and is best avoided. It is also important to avoid relying on any particular behavior that is not guaranteed by the specification. When, how, and if garbage collection occurs depends on the implementation of any given JavaScript engine.
let weakref = new WeakRef({name: 'domesy'.year: 24})
weakref.deref() // {name: 'domesy', year: 24}
weakref.deref().year / / 24
Copy the code
Logical operators and assignment expressions
&& =
let num1 = 5;
let num2 = 10;
num1 &&= num2;
console.log(num1); / / 10
/ / equivalent to the
num1 && (num1 = num2);
if (num1) {
num1 = num2;
}
Copy the code
| | =
let num1;
let num2 = 10;
num1 ||= num2;
console.log(num1); / / 10
/ / equivalent to the
num1 || (num1 = num2);
if(! num1) { num1 = num2; }Copy the code
?? =
- Null-value merge operator?? Only works if the value on the left is strictly null or undefined
let num1;
let num2 = 10;
let num3 = null; // undefinednum1 ?? = num2;console.log(num1); / / 10
num1 = false; num1 ?? = num2;console.log(num1); // falsenum3 ?? =123;
console.log(num3); / / 123
/ / equivalent to the
// num1 ?? (num1 = num2);
Copy the code
Value delimiter ES12
Recommendation: ⭐ ️
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
Copy the code
End
The special features of ES6~ES12 and how to use them have been completed. I hope this article can help you to understand them quickly. If you like, click 👍🏻 to support you.