ECMAScript 6
Variable deconstruction
ES6 allows you to extract values from arrays and formations and assign values to variables in a pattern known as deconstructed assignment.1.Array deconstructionconst array = ['Joe'.'bill'.'Cathy'.'Daisy'];
let [name1, name2, name3, name4] = array;
2.Object deconstructionconst array = {
name: 'Joe'.age: 20.jsTest: function() {
sonsole.log('Hello world'); }}let {name, age, jsTest} = array;
// Can also be destructed separately
let {jsTest} = array;
Copy the code
Template string
ES6 introduces a new way to declare strings` ` ' ' ""
1.The statementlet str = 'I am also a string';
2.A newline character can appear directly in the contentlet str = 'I am a substring';
3.Variable stitchinglet name = 'Joe';
let str = `${name}Good morning! `;
Copy the code
A simplified way of writing an object
ES6 allows variables and functions to be written directly inside curly braces as object properties and methods.let name = 'Joe';
let change = function() {
console.log("Hello world");
}
const data = {
name,
change,
jsTest() {
console.log("Hello world"); }}Copy the code
Arrow function
ES6 allows functions to be defined using [arrow] => ()// Declare the function
let jsTest = (a, b) = > {
return a + b;
}
// Call the function
let result = jsTest(1.2);
console.log(result); The difference between normal and arrow functions:1.thisIt's static,thisAlways refer to the scope in which the function declaration is madethisThe value of the2.Cannot be instantiated as a construct object3.You can't useargumentsvariable4.Abbreviation for arrow function - omits the parentheses when the parameter has only one statement; Omit the curly braces when the code has only one statementCopy the code
Default value Settings for function arguments
ES6 allows initialization of function parameter assignments1.Parameter initial value A parameter with a default value, usually placed later (unspoken rule)function jsTest(a, b, c = 100) {
return a + b + c;
}
let result = jsTest(1.2);
console.log(result);
2.Combined with deconstruction assignmentfunction jsTest({a = 100, b, c}) {
console.log(a);
console.log(b);
console.log(c);
}
jsTest({
b: 5.c: 10
})
console.log(result);
Copy the code
Rest parameters
ES6 introduces the REST argument, which is used to get arguments to functions, insteadarguments
// Rest parameters must be placed last
function jsTest(a, b, ... args) {
console.log(a);
console.log(b);
console.log(args);
}
jsTest(1.2.'a'.'b'.'c');
Copy the code
Extended operator
. The extension operator converts an array to a comma-separated sequence of arguments// Declare an array
const array = ['a'.'b'.'c'.'d'];
// Declare a function
function jsTest() {
console.log(arguments); } jsTest(... array);Copy the code
Symbol data type
ES6 introduces a new primitive data typeSymbolRepresents a unique value. It is the seventh data type of the JavaScript language and is a string-like type.SymbolThe characteristics of1.SymbolThe value of is unique and is used to resolve naming conflicts2.SymbolValue cannot be computed with other data3.SymbolThe defined object property cannot be usedfor. In loop traversal, but can be usedReflectOwnKeys to get all the key names of the object/ / create a Symbol
let s = Symbol(a);/ / Symbol. For creation
let s1 = Symbol.for('Joe');
let s1 = Symbol.for('Joe');
// Cannot be computed with other data
Copy the code
The iterator
An iterator is an interface that provides a unified access mechanism for a variety of different data structures. Any data structure that deploys the Iterator interface can perform variable manipulation.1.ES6 creates a new variable commandfor. The Iterator interface is mainly used forfor. Of writing// Declare an array
const array = ['a'.'b'.'c'.'d'];
/ / used for... Array of variables
for (let val of array) {
console.log(val);
}
/ / used for... Array of in variables
for (let val in array) {
console.log(val);
}
2.Raw data with Iterator interface (availablefor ofA).array B).arguments C).set D).map e).string f).typedarray g).nodelist3.How it works a). Create a pointer object that points to the starting position of the current data structure b). The first time the object's next method is called, the pointer automatically points to the first member of the data structure, C). The next method is then called repeatedly, moving the pointer back until it points to the last member, d). Each call to the next method returns an object containing the value and done attributeslet iterator = array[Symbol.iterator]();
// Call the next method of the object
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Copy the code
The generator
Generator functions are an asynchronous transformation solution provided by ES6 that has different syntactic behavior than traditional functions// A generator is just a special function
// Asynchronous programming pure callback functions
// The function code separator
function* jsTest() {
console.log("Hello world1");
yield 'It's sunny today.';
console.log("Hello world1");
yield 'It's sunny today 2';
console.log("Hello world1");
yield 'It's sunny today.';
console.log("Hello world1");
}
let iterator = jsTest();
iterator.next();
/ / variable
for (let val of jsTest()) {
console.log(val);
}
/** The generator function argument */
function* jsTest(arg) {
console.log(arg);
let one = yield 'It's sunny today.';
console.log(one);
let two = yield 'It's sunny today 2';
console.log(two);
let three = yield 'It's sunny today.';
console.log(three);
}
// Perform the fetch iterator object
let iterator = jsTest('AAA');
console.log(iterator.next());
console.log(iterator.next('BBB'));
console.log(iterator.next('CCC'));
Copy the code
Promise
PromiseAsynchrony is the new solution introduced in ES6. grammaticallyPromiseIs a constructor that encapsulates an asynchronous operation and can obtain the result of its success or failure.1.PromiseConstructor:Promise(excutor){}
2.Promise. Prototype. Then method3.PromiseMethod. The prototype. The catch// Instantiate the Promise object
const promise = new Promise(function (resolve, reject) {
setTimeout(() = > {
/ / success
// let data = 'I am some data success ';
// resolve(data);
/ / fail
let err = 'I am some data failure';
reject(err);
}, 1000);
});
// Call the then method of the Promise object
promise.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
});
/** cases (Promise encapsulates AJAX requests) */
/ / interface address: https://api.apiopen.top/getJoke
const promise = new Promise((resolve, reject) = > {
//1. Create objects
const xhr = new XMLHttpRequest();
/ / 2. The initialization
xhr.open("GET"."https://api.apiopen.top/getJoke");
/ / 3. Send
xhr.send();
//4. Bind events and process the response results
xhr.onreadystatechange = function () {
/ / determine
if (xhr.readyState === 4) {
// Determine the response status code
if (xhr.status === 200) {
// Indicates success
resolve(xhr.response)
} else {
// If it failsreject(xhr.status); }}}});// Specify the callback
promise.then(function (value) {
console.log(value);
}, function (reason) {
console.log(reason);
});
Copy the code
Set
ES6 provides new data structuresSet(Set). It is similar to an array in that the values of the individual members are unique. Collections implement the Iterator interface, so you can use "extension operators" and"for. Of..." I'm going to iterate.SetProperties and methods of:1.Size returns the number of elements in the collection2.Add adds a new element and returns the current collection3.deleteDelete element, return Boolean4.Has monitors whether the collection contains an element, returning Boolean// Declare a set
let s = new Set(a);let s2 = new Set(['a'.'b'.'c'.'a']);
Copy the code
Map
ES6 providesMapData structure. It is a collection of key-value pairs similar to objects. However, the scope of "keys" is not limited to strings; all types of values (including objects) can be used as keys.MapAlso implements the Iterator interface, so you can use "extension operators" and"for. Of..." I'm going to iterate.MapProperties and methods of:1.Size returns the number of elements in the collection2.Add adds a new element and returns the current collection3.deleteDelete element, return Boolean4.Has monitors whether the collection contains an element, returning Boolean5.Clear Clears the collection and returnsundefined
// Declare a Map
let m = new Map(a);Copy the code
Class class
ES6 provides a more traditional language approach, introducing the concept of classes as templates for objects. throughclassKeyword that can define a class. Basically,ES6theclassThink of it as knowing a grammar, and most of its functions,ES5You can do it all. NewclassWriting just makes writing object prototypes clearer and more like object-oriented programming syntax. 1.classThe statement class 2.constructorDefine the constructor to initialize 3.extendsCall the parent constructor 4.superCall the parent constructor 5.staticDefine static methods and properties. 6. Superclass methods can be overriddenCopy the code
ECMAScript 7
Array.prototype.includes
The includes method checks whether an array contains an element and returns a Bohr value//includes
const dataArray = ['a'.'b'.'c'.'d'];
/ / determine
console.log(dataArray.includes('a'));
console.log(dataArray.includes('e'));
// ** exponents 2 ** 10 = math.pow (2, 10) are equal
console.log(2支那10);
console.log(Math.pow(2.10));
Copy the code
ECMAScript 8
Async and await
async 和 awaitThe combination of the two grammars makes asynchronous code behave like synchronous code.1.asyncFunction a).aysnc returns the promise object b). The result of the promise object is determined by the return value executed by asyCN/ / async function
async function jsTest() {
// Returns either a Promise object or a success Promise object
// return;
// Throws an error and returns a failed Promise
// throw new Error(' Error ');
// Return a Promise object
return new Promise((resolve, reject) = > {
// Success data
resolve('success');
// Failed data
// reject(' reject ');})}const result = jsTest();
// Call the then method
result.then(value= > {
console.log(value);
}, reason= > {
console.log(result);
});
2.awaitExpression a).await must be written inasyncA) await b) await C) await D) await an exception will be thrown if the promise failstry. Catch processing// Create a Promise object
const promise = new Promise((resolve, reject) = > {
resolve('success');
});
//await to be placed in async function
async function jsTest() {
let result = await promise;
console.log(result);
}
// Call the function
jsTest();
Copy the code
Object method extension
Object values, Object. Entries, Object. GetOwnPropertyDescriptors
1.ObjectThe.values() method returns an array of all enumerable property values for a given object2.ObjectThe.entries() method returns an array of the given object's own traversable properties [key, value]3.Object. GetOwnPropertyDescriptors this method returns the specified object all its attributes describe objects// Declare objects
const user = {
name: 'Joe'.array: ['a'.'b'.'c'.'d']}// Get all the keys of the object
console.log(Object.keys(user));
// Get all the values of the object
console.log(Object.values(user));
//entries
console.log(Object.entries(user));
// The object attributes describe the object
console.log(Object.getOwnPropertyDescriptors(user));
Copy the code
ECMAScript 9
Object is a
Rest parameters and spread extension operators have been introduced in ES6, but only for arrays, while ES9 provides array-like Rest parameters and extension operators for objectsfunction jsTest({ val1, val2, ... val }) {
console.log(val1);
console.log(val2);
console.log(val);
}
jsTest({
val1: 'a'.val2: 'b'.val3: 'c'.val4: 'd'
});
Copy the code
Regular extension – Named capture groups
// Declare a string
let str = '<span value="world">Hello</span>';
// Extract value and label text
const reg = /<span value="(.*)">(.*)<\/span>/;
/ / execution
const result = reg.exec(str);
console.log(result);
Copy the code
Regular extension – Reverse assertion
// Declare a string
let str = '11111 just a little bit 2222 la la la 33333 Hello ';
// Forward assertion
const reg = /\d+(? Hi =) /;
const result = reg.exec(str);
// Reverse assertion
const reg = / (? < =) \ d + /;
const result = reg.exec(str);
console.log(result);
Copy the code
ECMAScript 10
Object.fromEntries
Object. FromEntries and ES8ObjectIs the difference between entriesObjectFromEntries converts a two-dimensional array to an object in ES8Object. Entries convert objects into two-dimensional arrays// A two-dimensional array
const result = Object.fromEntries(
[
['name'.'Joe'],
['age'.'20']]);//Map
const map = new Map(a); map.set('name'.'Joe');
const result = Object.fromEntries(map);
console.log(result);
Copy the code
Two extension methods for string trimStart and trimEnd
TrimStart is removing whitespace from the left of the string and trimEnd is removing whitespace from the right of the string//trim
let str = " hello world ";
console.log(str);
console.log(str.trimStart());
console.log(str.trimEnd());
Copy the code
Array methods flat and flatMap
//flat
// Convert a multidimensional array to a lower-dimensional array
const arr = [1.2.3.4The [[5.6].7.8.9].10];
The default value is 1
console.log(arr.flat(2));
//flatMap
// De-dimensionalize the Map result
const arr = [1.2.3.4];
const result = arr.flatMap(item= > [item * 10]);
console.log(result);
Copy the code
The Symbol’s expansion Symbol. The prototype. The description
// Get the string description of Symbol
/ / create a Symbol
let s = Symbol('Joe');
console.log(s.description);
Copy the code
ECMAScript 11
Private property
class Person {
// Public attributes
name;
// Private attributes
#age;
#weight;
// constructor
constructor(name, age, weight) {
this.name = name;
this.#age = age;
this.#weight = weight; }}/ / instantiate
const user = new Person('Joe'.20.'50kg');
console.log(user);
console.log(user.name);
console.log(user.#age);
console.log(user.#weight);
Copy the code
Promise.allSettled
// This method takes an array of Promises and returns a Promise object that always returns a successful state.
/ / sample
const p1 = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve('It worked - 1');
}, 1000);
});
const p2 = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve('It worked - 2')}); });const result = Promise.allSetted([p1, p2]);
// The difference with promise. all is that the all method is judged according to the state of each object. If there is a failure, it is a failure.
Copy the code
String extension String. Prototype. MatchAll
const str = `http://localhost:3000? Id =1&name= age=20;
// Create a re
const reg = / \? id=(.*?) &name=(.*?) &age=(.*?) $/sg;
const result = str.matchAll(reg);
for (let value of result) {
console.log(value);
}
Copy the code
Optional chain operator
/ /? .
// No error is reported even if no object is passed in
const user = {
name: 'Sketchy'.action: {
sing: 'sing'.jump: 'jump'}}function jsTest(user) {
constresult = user? .action? .sing;console.log(result);
}
jsTest(user);
Copy the code
Dynamic import
// Import when needed
// Get the element
const btn = document.getElemntById('btn');
btn.onclick = function() {
import('./hello.js').then(module= > {
module.hello();
});
}
Copy the code
The new data type BigInt
// Big integer BigInt
let n = 500n;
console.log(n, typeof(n));
/ / function
let n = 123;
console.log(BigInt(n)); // Convert the data type
// Large numeric operations
let max = Number.MAX_SAFE_INTEGER;
console.log(BigInt(max) + 1); // An error was reported. The operation cannot be performed directly with ordinary data types
console.log(BigInt(max) + BigInt(1)); // This will do
Copy the code
This global globalThis
// globalThis always points to a global object
console.log(globalThis);
Copy the code