当前位置:网站首页>Es6---es6 content details
Es6---es6 content details
2022-07-06 15:22:00 【Cirrod】
1. ES6
1.1 let and const command
1.1.1 let
characteristic
Variables cannot be declared repeatedly
let star=' Luo Xiang ';
let star=' Piglets ' //error
let There are block-level scopes
Block level scope overall situation , function ,eval
{
let girl=' Zhou Yangqing '
}
console.log(girl) //error
Not just for curly braces , for example if(){},while(){},else{},for(){} Inside
No variable advance
console.log(song) //error
let song=' Love people '
Does not affect the scope chain
let school='abc'
function fn(){
console.log(school) //abc
}
Case study
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<div class="item" style="width: 50px;height: 50px;background-color: red"></div>
<div class="item" style="width: 50px;height: 50px;background-color: red"></div>
<div class="item" style="width: 50px;height: 50px;background-color: red"></div>
</div>
<script>
let items=document.getElementsByClassName("item");
for (var i=0;i<items.length;i++){
items[i].onclick=function (){
items[i].style.backgroundColor='pink';
}
}
console.log(windows.i) //3
// When var=3 When , Click the event to start looking for the outer scope , Can't find , Namely windows.i, Now it's 3, If it is let i, Has block level scope , So every touch event i It's all different .
</script>
</body>
</html>
1.1.2 const
characteristic
declare constant
const A = 'abc'
Be sure to assign the initial value
General constants use uppercase ( Hidden rules )
The value of a constant cannot be modified
Also has block level scope
{
const pyaler = 'uzi'
}
console.log(player) //error
For the element modification of arrays and objects , It does not count as a modification of the constant
const team = ['uzi','MXLG','Ming','Letme'];
team.push('Meiko'); // Don't complain , The constant address has not changed
const Actually guaranteed , It's not that the value of a variable can't be changed , Instead, the memory address that the variable points to holds the same data .
For simple types of data ( The number 、 character string 、 Boolean value ), The value is stored at the memory address that the variable points to , So it's equivalent to a constant . But for data of composite type ( Mainly objects and arrays ), The memory address that the variable points to , It's just a pointer to the actual data ,const It can only be guaranteed that the pointer is fixed ( Always point to another fixed address ), As for whether the data structure it points to is variable , It's totally out of control . therefore , You have to be very careful when declaring an object as a constant .
1.2 Deconstruct assignment
Introduce
ES6 Allows you to extract values from arrays and objects according to certain patterns , Assign values to variables , This is called deconstruction assignment .
The property or method name of the array or object to be deconstructed and assigned must correspond
The deconstruction of arrays :
const F4 = [' Little Shenyang ',' Lennon ',' Zhao si ',' Song Xiaobao ']
let [xiao,liu,zhao,song] = F4;
console.log(xiao)
console.log(liu)
console.log(zhao)
console.log(song)
Object deconstruction
const zhao = {
name : ' Zhao Benshan ',
age: ' An unknown ',
xiaopin: function(){
console.log(" I can play sketches ")
}
}
let {name,age,xiaopin} = zhao;
console.log(name);
console.log(age);
console.log(xiaopin);
1.3 Template string (``)
characteristic
Statement
let str = ` I'm also a string `
console.log(str,typeof str);
Line breaks can appear directly in the content
let str = `<ul>
<li>RHF</li>
<li>RHF</li>
</ul>`;
Variable splicing
let lovest = 'RHF';
let out = `${lovest} Is the most handsome `;
console.log(out) //RHF Is the most handsome
1.4 Simplified writing of objects
Introduce
ES6 Allow in braces , Write variables and functions directly , Properties and methods as objects , This kind of writing is more concise
characteristic
let name = 'aaa';
let change = function(){
console.log('aaa');
}
const school = {
name,
change,
improve(){
consolg.log('bbb');
}
}
1.5 Arrow function ( Omit function)
Introduce
ES6 Arrows are allowed (=>) Defined function
characteristic
this Is static ,this Always point to... Under the scope where the function is declared this Value
function A(){
console.log(this.name)
}
let B = () => {
console.log(this.name);
}
window.name = ' Silicon Valley ';
const school = {
name: 'ATGUIGU'
}
// Call directly
A() // Silicon Valley
B() // Silicon Valley
//call
A.call(school); //ATGUIGU
B.cal(school); // Silicon Valley
Cannot instantiate an object as a construct
let A(name,age) => {
this.name=name;
this.age=age;
}
let me = new A('xiao',123);
console.me //error
Out of commission arguments Variable
let fn = () => {
console.log(arguments);
}
fn(1,2,3) //error
Abbreviation
Omit parentheses , When there is only one formal parameter
let add = n => {
return n + 1;
}
Omit the curly brackets , When there is only one statement in contemporary code body , here return You must also omit , Function also automatically returns the result
let add = n => n+1;
1.5.1. The suitability of arrow function
1. The arrow function is suitable for this Unrelated callbacks , Timer , Callback of array method
2. The arrow function is not suitable for this About callbacks , Event callback , Object methods
1.6 Function parameter defaults
Introduce
ES6 It is allowed to assign initial values to function parameters
characteristic
You can assign initial values to formal parameters , The general position depends on the back ( Hidden rules )
function add(a,b,c=12){
return a+b+c;
}
let result = add (1,2);
console.log(result) // 15
Combined with deconstruction assignment
function A({host='127.0.0.1',username,password,port}){
console.log(host+username+password+port)
}
A({
username:'ran',
password:'123456',
port:3306
})
1.7 rest Parameters
Introduce
ES6 introduce rest Parameters , To get arguments to a function , Used in place of arguments
arguments The returned result is the object
rest Parameter returns an array ( Conducive to array api operation , such as fiter,some,every,map)
characteristic
function date(...args){
console.log(args);
}
date('aaa','bbb','ccc');
matters needing attention
rest The parameter must be placed at the end of the parameter
function fn(a, b, ...name) {
console.log(a);
console.log(b);
console.log(name);
}
fn(1, 2, 3, 4, 5);
1.8 Extension operator
Introduce
The extension operator can convert an array into a comma separated sequence of parameters
characteristic
const tfboys=['AA','BB','CC']
function chunwan(){
console.log(arguments);
}
chunwan(...tfboys); //0:'AA' 1:'BB' 2:'CC'
application
Merging of arrays
const A = ['aa','bb'];
const B = ['cc','dd'];
const C = [...A,...B];
console.log(C) //[aa,bb,cc,dd]
Clone of array ( Shallow copy )
const A = ['a','b','c'];
const B = [...A];
console.log(B) //[a,b,c]
Convert a pseudo array to a real array
const A = documents.querySelectorAll('div');
const B = [...A];
console.log(B) // [div,div,div]
1.9 Symbol
Introduce
ES6 A new type of raw data is introduced Symbol, Represents a unique value . It is JavaScript The seventh data type of language , Is a data type similar to a string .
Symbol characteristic :
Symbol Is unique , Used to resolve naming conflicts
Symbol Value cannot be calculated with other data
Symbol Defined object properties cannot be used for…in Loop traversal , But you can use Reflect.ownKeys To get all the key names of the object
characteristic
establish
let s = Symbol('aa');
let s2= Symbol('aa');
console.log(s===s2) //false
let s3 = Symbol.for('bb');
let s4 = Symbol.for('bb');
comsole.log(s3===s4) ///true
Cannot operate with other data
let result = s + 100 //error
let result = s > 100 //error
let result = s + s //error
Symbol Built in values
class Person {
static [Symbol.hasInstance](param){
console.log(param);
console.log(" I was used to detect ");
return false;
}
}
let o = {};
console.log(o instanceof Person); // I was used to detect ,false
application ( Security , Prevent adding properties or methods with the same name to objects )
Add methods to objects in mode 1 :
let game = {
name : 'ran'
}
let methods = {
up:Symbol()
down:Symbol()
}
game[methods.up]=function(){
console.log('aaa');
}
game[methods.down]=function(){
console.log('bbb');
}
console.log(game) // name: 'ran',Symbol(),Symbol()
Add methods to objects in mode 2
let youxi = {
name: ' Werewolf killing ',
[Symbol('say')]:function(){//symbol() Is an expression , Dynamic values , With braces
console.log(' Assad ')
}
}
console.log(youxi) // name:' Werewolf killing ',Symbol(say)
review
js Of 7 Type of data
u undefine
s string symbol
o object
n null number
b boolean
1.10 iterator
Introduce
iterator (lterator) It's an interface , Provide unified access mechanism for different data structures . Any data structure only needs to be deployed lterator Interface , You can complete the traversal operation .
ES6 Creates a new traversal command for...of loop ,iterator Main interface supply for...of consumption
Original possession Iterator Interface data ( You can use for of Traverse )
Array
Arguments
Set
Map
String
TypeArray
NodeList
principle : Create a pointer object , Point to the starting position of the data structure , First call ==next()== Method , The pointer automatically points to the first member of the data structure , Next, call next(), The pointer moves all the way back , Until it points to the last member , No call next() Returns a containing value and done Object of property
characteristic
const xiyou=['AA','BB','CC','DD'];
// for(let v of xiyou){
// console.log(v) // 'AA','BB','CC','DD' //for in The key name is saved ,for of The key value is saved
// }
let iterator = xiyou[Symbol.iterator]();
console.log(iterator.next()); //{
{value:' Tang's monk ',done:false}}
console.log(iterator.next()); //{
{value:' The Monkey King ',done:false}}
application
const banji = {
name : " The ultimate class ",
stus: [
'aa',
'bb',
'cc',
'dd'
],
[Symbol.iterator](){
let index = 0;
let _this = this;
return {
next: () => {
if(index < this.stus.length){
const result = {value: _this.stus[index],done: false};
// Subscript self increasing
index++;
// Return results
return result;
}else {
return {value: underfined,done:true};
}
}
}
}
}
for(let v of banji){
console.log(v); // aa bb cc dd
}
1.11 generator
Introduce
The generator function is ES6 An asynchronous programming solution provided by , Grammatical behavior is totally different from traditional function , It's a special function
Asynchronous programming : File operations Network operating (ajax,request) Database operation
characteristic
function * gen (){ // Function names and function One in the middle *
// The first paragraph
yield ' Ears '; //yield Is the separator of the function code
// The second paragraph
yield ' tail ';
// The third paragraph
yield ' It's strange. ';
// The fourth paragraph
}
let iterator = gen();
console.log(iteretor.next());
//{value:' Ears ',done:false} next() Execute the first paragraph , And back to yield Value after
console.log(iteretor.next()); //{value:' tail ',done:false}
console.log(iteretor.next()); //{value:' It's strange. ',done:false}
application
The parameters of the generator function are passed
function * gen(args){
console.log(args);
let one = yield 111;
console.log(one);
let two = yield 222;
console.log(two);
let three = yield 333;
console.log(three);
}
let iterator = gen('AAA');
console.log(iterator.next());
console.log(iterator.next('BBB')); //next In the middle of BBB Will serve as a yield 111 Return result of
console.log(iterator.next('CCC')); //next In the middle of CCC Will serve as a yield 222 Return result of
console.log(iterator.next('DDD')); //next In the middle of DDD Will serve as a yield 333 Return result of
example 1: Use the generator function to solve the callback hell problem
function one(){
setTimeout(()=>{
console.log('111')
iterator.next()
},1000)
}
function two(){
setTimeout(()=>{
console.log('222')
iterator.next();
},2000)
}
function three(){
setTimeout(()=>{
console.log('333')
iterator.next();
},3000)
}
function * gen(){
yield one();
yield two();
yield three();
}
let iterator = gen();
iterator.next();
example 2: Simulate asynchronous data acquisition
function one(){
setTimeout(()=>{
let data=' User data ';
iterator.next(data)
},1000)
}
function two(){
setTimeout(()=>{
let data=' Order data ';
iterator.next(data)
},2000)
}
function three(){
setTimeout(()=>{
let data=' Commodity data ';
iterator.next(data)
},3000)
}
function * gen(){
let users=yield one();
console.log(users)
let orders=yield two();
console.log(orders)
let goods=yield three();
console.log(goods)
}
let iterator = gen();
iterator.next();
1.12 Promise
Introduce
Promise yes ES6 The introduction of a new solution to asynchronous programming . Grammatically Promise It's a constructor , Used to encapsulate asynchronous operations and obtain the results of their success or failure .
characteristic
Basic characteristics
<script>
const p =new Promise((resolve, reject)=>{
setTimeout(()=>{
let data=' Database data '
// resolve(data);
reject(data);
})
})
p.then(function (value){ // If successful, execute the first callback function , If it fails, execute the second one
console.log(value)
},function (reason){
console.error(reason)
})
</script>
Promise.then() Method
<script>
const p =new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve(' User data ');
})
});
//then() The function actually returns a Promise object
//1. When the callback function returns yes or no Promise Type properties when ,Promise The object status is success (resloved),then() The return value of the function is the success value of the object , Such as return 123, Back to Promise The object value is 123, If there is no return value , yes undefined
//2. When the callback function returns Promise When an object of type ,then() Function returns Promise The state value of the object is this Promise The state value of the object , So is the success value .
//3. When the callback function callback , If the exception thrown , be then() The return value status of the function is also rejected
let result = p.then(value => {
console.log(value)
// return 123;
// return new Promise((resolve, reject) => {
// resolve('ok')
// })
throw 123
},reason => {
console.log(reason)
})
console.log(result);
</script>
Promise.catch() Method
//catch() Function has only one callback function , It means if Promise If the object status is failed, it will call catch() Method and call the callback function
<script>
const p = new Promise((resolve, reject) => {
setTimeout(()=>{
reject(' Error ')
},1000)
})
p.catch(reason => {
console.log(reason)
})
</script>
application : send out AJAX request
<script>
//ajax Request to return a promise
function sendAjax(url){
return new Promise((resolve, reject) => {
// Create objects
const x =new XMLHttpRequest();
// initialization
x.open('GET',url);
// send out
x.send();
// Time bound
x.onreadystatechange = ()=>{
if(x.readyState === 4 ){
if(x.status >= 200 && x.status < 300){
// success
resolve(x.response)
}else {
// Failure
reject(x.status)
}
}
}
})
}
// test
sendAjax("https://api.apiopen.top/getJoke").then(value => {
console.log(value)
},reason => {
console.log(reason)
})
</script>
1.13 aggregate ( It's essentially an object )
1.13.1 Set
Introduce
ES6 Provides a new data structure set( aggregate ). It's like an array , But the values of members are unique , The collection is implemented iterator Interface , So you can use 「 Extension operator 』 and 「 for…of…』 Traversal , Properties and methods of a collection :
size Returns the number of elements in the collection
add Add a new element , Returns the current collection
delete Remove elements , return boolean value has Detect whether the collection contains an element , return boolean value
characteristic
<script>
let s = new Set();
let s2 = new Set(['A','B','C','D'])
// Element number
console.log(s2.size);
// Add new elements
s2.add('E');
// Remove elements
s2.delete('A')
// testing
console.log(s2.has('C'));
// Empty
s2.clear()
console.log(s2);
</script>
application
<script>
let arr = [1,2,3,4,5,4,3,2,1]
//1. Array weight removal
let result = [...new Set(arr)]
console.log(result);
//2. intersection
let arr2=[4,5,6,5,6]
let result2=[...new Set(arr)].filter(item=>{
let s2=new Set(arr2);//456
if(s2.has(item)){
return ture;}
else {
return false;
}
});
Simplify the code :
let result2 = [...new Set(arr)].filter(item => new Set(arr2).has(item))
console.log(result2);
//3. Combine
let result3=[new Set([...arr,...arr2])]
console.log(result3);
//4. Difference set
let result4= [...new Set(arr)].filter(item => !(new Set(arr2).has(item)))
console.log(result4);
</script>
1.13.2 Map( Upgraded object )
Introduce
ES6 Provides Map data structure . It's like an object , It's also a set of key value pairs . however “ key ” Is not limited to strings , Various types of values ( Including objects ) Can be used as a key .Map It has also been realized. iterator Interface , So you can use 『 Extension operator 』 and 「for…of…』 Traversal .Map Properties and methods of .
characteristic
<script>
let m = new Map();
m.set('name','ran');
m.set('change',()=>{
console.log(' change !')
})
let key={
school:'atguigu'
}
m.set(key,[' Chengdu ',' Xi'an ']);
//size
console.log(m.size);
// Delete
m.delete('name');
// obtain
console.log(m.get('change'));
// // Empty
// m.clear()
// Traverse
for(let v of m){
console.log(v);
}
</script>
1.14 Class
1.14.1 First experience
Introduce
ES6 Provides a more traditional approach , Introduced Class( class ) The concept , Template as object . adopt class keyword , Classes can be defined . Basically ,ES6 Of class Can be seen as just a grammar sugar , Most of its functions ,ES5 Can do it , new class The writing method is just to make the writing method of the object prototype clearer 、 It's more like the syntax of object-oriented programming .
characteristic
<script>
class shouji {
// Construction method , The name cannot be changed
constructor(brand,price) {
this.brand=brand;
this.price=price
}
// Method must use this syntax , Out of commission es5 The complete form of the object
call(){
console.log(' I can call ')
}
}
let A = new shouji('1+',1999);
console.log(A)
</script>
1.14.2 Static members
Static members and methods belong to classes , Does not belong to an instantiated object
<script>
class Phone{
// Static attribute
static name=' mobile phone ';
static change(){
conse.log(" I can change the world ")
}
}
let nokia = new Person();
console.log(nokia.name);//underfine
console.log(Phone.name)// mobile phone
</script>
1.14.3 Constructor inheritance (es5)
<script>
function Phone(brand,price){
this.brand=brand;
this.price=price;
}
Phone.prototype.call=function (){
console.log(" I can call ");
}
function SmartPhone(brand,price,color,size){
Phone.call(this,brand,price);
this.color=color;
this.size=size;
}
// Set child constructor prototype
SmartPhone.prototype=new Phone;
SmartPhone.prototype.constructor=SmartPhone;
// Declare subclass methods
SmartPhone.prototype.photo = function (){
console.log(' I can play games ');
}
const chuizi = new SmartPhone(' The hammer ',2499,' black ','5.5inch')
console.log(chuizi);
</script>
1.14.4 Class Class inheritance (es6)
<script>
class Phone{
constructor(brand,price) {
this.brand=brand;
this.price=price;
}
// Member properties of the parent class
call(){
console.log(' I can call ')
}
}
class SmartPhone extends Phone{
constructor(brand,price,color,size) {
super(brand,price);
this.color=color;
this.size=size;
}
photo(){
console.log(' Taking pictures ');
}
playGame(){
console.log(' Play the game ');
}
}
const xiaomi=new SmartPhone(' millet ',1999,' black ','4.7inch')
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();
</script>
1.14.5 Subclass's rewriting of parent methods
<script>
class Phone{
constructor(brand,price) {
this.brand=brand;
this.price=price;
}
// Member properties of the parent class
call(){
console.log(' I can call ')
}
}
class SmartPhone extends Phone{
constructor(brand,price,color,size) {
super(brand,price);
this.color=color;
this.size=size;
}
photo(){
console.log(' Taking pictures ');
}
playGame(){
console.log(' Play the game ');
}
// rewrite !
call(){
console.log(' I can make video calls ')
}
}
const xiaomi=new SmartPhone(' millet ',1999,' black ','4.7inch')
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();
</script>
1.14.6 get( Triggered when data is read ) and set( Triggered when the data is modified ) Set up
<script>
class Phone{
get price(){
console.log(" The price was read ")
return 'I LOVE YOU'
}
set price(val){
console.log(' The price has been revised ')
return val;
}
}
// Instantiate objects
let s = new Phone();
s.price=12
// console.log(s.price) // It's actually called price Method
</script>
1.15 Numerical expansion
<script>
// Number.EPSILON yes JavaScript Minimum accuracy of , The value of the property is close to 2.22044...E-16
function equal(a,b){
if(Math.abs(a-b) < Number.EPSILON){
return true;
}else {
return false;
}
}
console.log(equal(0.1 + 0.2 === 0.3)) //false
console.log(equal(0.1+0.2,0.3)) //true
// Binary and octal
let b = 0b1010; //2 Base number
let o = 0o777; //8 Base number
let d = 100; //10 Base number
let x = 0xff; //16 Base number
console.log(x) //255
// Check whether a number is finite
console.log(Number.isFinite(100)); //true
console.log(Number.isFinite(100/0)); //false
console.log(Number.isFinite(Infinity)); //false
// Check whether a value is NaN
console.log(Number.isNaN(123)) //false
// String to integer
console.log(Number.parseInt('5213123love')); //5213123
console.log(Number.parseFloat('5.123123 Artifact ')); //5.123123
// Judge whether it is an integer
console.log(Number.isInteger(5)); //true
console.log(Number.isInteger(2.5)); //false
// Erase the decimal part
console.log(Math.trunc(3.45345345345)) //3
// Check whether a number is positive 、 negative 、 still 0
console.log(Math.sign(100)) //1
console.log(Math.sign(0)) //0
console.log(Math.sign(-123)) //-1
</script>
1.16 Object method extension
<script>
//1.Object.is Determine whether the two values are exactly equal
console.log(Object.is(120,120)) //true
console.log(Object.is(NaN,NaN)) //false
//2.Object.assign Merge of objects
const a = {
name:'ran',
age:12
}
const b = {
pass:'i love you'
}
console.log(Object.assign(a,b)) //{name:'ran',age:'12',pass:'i love you'}
//3.Object.setPrototypeOf Set prototype object Object.getPrototypeof
const school = {
name:' Silicon Valley '
}
const cities = {
xiaoqu:[' Beijing ',' Shanghai ']
}
Object.setPrototypeOf(school,cities)
console.log(Object.getPrototypeOf(school)) //{xiaoqu: Array(2)}
console.log(school) //{name: " Silicon Valley "}
</script>
1.17 modularization
1.17.1 Basic introduction
Introduce
Modularization means that a large program file , Split into many small files , Then combine the small files .
The benefits of modularity :
Prevent naming conflicts
Code reuse
High maintenance
Modular standardized products
ES6 Previous modular specifications include :
CommonJS ====> NodeJS、Browserify
AMD ====> requireJS
CMD ====> seaJS
grammar
The module function is mainly composed of two commands :export and import
export Command is used to specify the external interface of the module
import Commands are used to enter functions provided by other modules
export let school = ' Silicon Valley '
export function teach(){
console.log(' Teaching skills ')
}
<script type="module">
import * as m1 from "./src/js/m1.js";
console.log(m1);
</script
1.17.2 Expose syntax summary
Unified exposure
// Unified exposure
let school = ' Silicon Valley ';
function findjob(){
console.log(' Find a job ');
}
//export {school,findjob}
Default exposure
// Default exposure
export default {
school:'ATGUIGU',
change:function(){
console.log(' We can change you ')
}
}
1.17.3 Introduce syntax summary
General import method
import * as m1 from "./src/js/m1.js"
import * as m2 from "./src/js/m2.js"
import * as m3 from "./src/js/m3.js"
Deconstruction assignment method
import {school,teach} from "./src/js/m1.js"
import {school as guigu,findJob} from "./src/js/m2.js"
import {default as m3 } from "./src/js/m3.js"
Simple form ( For default exposure only )
import m3 from "./src/js/m3.js"
1.17.4 Modular way 2
<script src="./src//js/app.js" type=modeule></script>
2. ES7
Introduce
Array.prototype.includes: Used to detect whether the array contains an element , Returns a Boolean value
stay ES7 Introducing the exponential operator **, Used to implement power operation , Function and Math.pow The result is the same
application
<script>
//include
const mingzhu = [' Journey to the west ',' A dream of red mansions ',' Water margin ',' The romance of The Three Kingdoms ']
console.log(mingzhu.includes(' Journey to the west ')) //true
console.log(mingzhu.includes(' The Plum in the Golden Vase ')) //false
//**
console.log(2**10) // 1024
</script>
3. ES8
3.1 async function
Introduce
async and await The combination of the two syntax can make asynchronous code like synchronous code
async function :
async The return value of the function is promise object
async Back to promise The result value of the object is determined by async The return value of the function execution determines
characteristic
async function fn(){
//1. If you return a non - Promise The object of , be fn() The returned result is the success status Promise object , The value is the return value
//2. If you return a Promise object , be fn() The returned result is similar to the internal Promise The result of the object is the same
//3. If the return is an error thrown , be fn() What is returned is in the failed state Promise object
return new Promise((resolve,reject)=>{
resolve(' Success data ');
});
}
const result = fn();
result.then(value=>{
console.log(value) // Success data
},reason=>{
console.log(reason)
})
3.2 await expression
Introduce
await Must be on async Function
await The expression on the right is usually promise object
await You can return to the right side promise The value of success
await On the right side of the promise If it fails , Will throw an exception , Need to pass through try…catch Capture processing
characteristic
1. // 1 establish promise object
const p = new Promise((resolve, rejiect) => {
resolve(' success !')
});
// await Must be in async In the function
async function main() {
let result = await p;
console.log(result);
}
main();
2.
<script>
// establish Promise object
const p = new Promise((resolve, reject) => {
// resolve(" The value of success ")
reject(" failed ")
})
//await Must be on async Function
async function main() {
try {
let res = await p;
console.log(res);
} catch (e) {
console.log(e);
}
}
// Call function
main() // failed
</script>
application : send out AJAX request
<script>
//ajax Request to return a promise
function sendAjax(url){
return new Promise((resolve, reject) => {
// Create objects
const x =new XMLHttpRequest();
// initialization
x.open('GET',url);
// send out
x.send();
// Time bound
x.onreadystatechange = ()=>{
if(x.readyState === 4 ){
if(x.status >= 200 && x.status < 300){
// success
resolve(x.response)
}else {
// Failure
reject(x.status)
}
}
}
})
}
//async And await test
async function main(){
let result = await sendAjax("https://api.apiopen.top/getJoke")
console.log(result);
}
main()
</script>
3.3 ES8 Object method extension
<script>
const school = {
name:' Silicon Valley ',
cities:[' Beijing ',' Shanghai ',' Shenzhen '],
xueke:[' front end ','Java',' big data ',' Operation and maintenance ']
};
// Get all the keys of the object
console.log(Object.keys(school));
// Get all the values of the object
console.log(Object.values(school));
//entries, Used to create map
console.log(Object.entries(school));
console.log(new Map(Object.entries(school)))
// Object property description object
console.log(Object.getOwnPropertyDescriptor(school))
const obj = Object.create(null,{
name:{
value:' Silicon Valley ',
// Attribute characteristics
writable:true// Is it possible to write
configurable:true,// Can I delete
enumerable:true,// Can I enumerate
}
})
</script>
4. ES9
4.1 Operation extender and rest Parameters
<script>
function connect({host,port,...user}){
console.log(host);
console.log(port);
console.log(user)
}
connect({
host:'127.0.0.1',
port:3306,
username:'root',
password:'root',
type:'master'
}) //127.0.0.1 3306 {username: "root", password: "root", type: "master"}
</script>
<script>
const AA={
username:'ran'
}
const BB={
password:'lyyrhf'
}
const CC={
job:'Java'
}
const D={...AA,...BB,...CC};
console.log(D) //{username: "ran", password: "lyyrhf", job: "Java"}
</script>
4.2. Regular extension - Named group capture
5. ES10
5.1 Object extension method
<script>
// Two dimensional array
const res = Object.fromEntries([
['name','RHF'],
['cities',' Chengdu ',' wuhan ']
])
console.log(res) //{name: "RHF", cities: " Chengdu "}
//Map
const m = new Map();
m.set('name','ranhaifeng')
const result = Object.fromEntries(m)
console.log(result); //{name: "ranhaifeng"}
</script>
5.2 String extension method
<script>
//trim
let str= ' asd '
console.log(str) //asd
console.log(str.trimStart()) //asd Clear the short space
console.log(str.trimEnd()) // asd Clear trailing spaces
</script>
5.3 flat And flatMap
<script>
const arr = [1,2,3,[4,5,6,[7,8,9]]]
// The parameter is depth , It's a number
console.log(arr.flat(2)) //[1,2,3,4,5,6,7,8,9]
const arr2=[1,2,3,4]
const result = arr2.flatmap(item => [item * 10]); // If map The result is a multidimensional array that can be flat It is the combination of two operations
</script>
5.4 Symbol Of description
Introduce
example
let s = Symbol(' Silicon Valley ');
console.log(s.description) // Silicon Valley
5.5 Private property
<script>
class Person {
// Public attribute
name;
// Private property
#age;
#weight;
// Construction method
constructor(name, age, weight) {
this.name = name;
this.#age = age;
this.#weight = weight;
}
intro(){
console.log(this.name);
console.log(this.#age);
console.log(this.#weight);
}
}
// Instantiation
const girl = new Person(' Chen ', 18, '45kg');
console.log(girl.#age) //error
console.log(girl); //Person{name: " Chen ", #age: 18, #weight: "45kg"}
girl.intro(); // Chen 18 45kg
</script>
5.6 Promise
<script>
// Declare two promise object
const p1 = new Promise((resolve, reject) => {
setTimeout(()=>{
resolve(' Commodity data -1')
},1000)
})
const p2 = new Promise((resolve, reject) => {
setTimeout(()=>{
reject(' Something went wrong !')
},1000)
})
// call allsettled Method : The result returned is always a success , And the results and states of asynchronous tasks exist
const res = Promise.allSettled([p1,p2]);
console.log(res)
// Promise {<pending>}
// __proto__: Promise
// [[PromiseState]]: "fulfilled"
// [[PromiseResult]]: Array(2)
// call all Method : The returned result is according to p1、p2 The state of , If they all succeed , The successful , If one fails , The failure , The result of failure is failure Promise Result
const result = Promise.all([p1,p2])
console.log(result)
</script>
5.7 Optional chain operator
// It is equivalent to a judge , If the front one has , Go to the next level
function main(config){
const dbHost = config?.db?.host
console.log(dbHost) //192.168.1.100
}
main({
db:{
host:'192.168.1.100',
username:'root'
},
cache:{
host:'192.168.1.200',
username:'admin'
}
})
5.8 dynamic import
btn.onclick = function(){
// Not introduced before use , Dynamic introduction , I'm actually going to return one Promise object
import('./hello.js').then(module=>{
module.hello();
})
}
5.9 BigInt type
// Big integer
let n = 521n;
console.log(n,typeof(n)) // 521n n
// function
let n = 123;
console.log(BigInt(n)) // 123n // Do not use floating point type , Only use int
// Large value operation
let max = Number.MAX_SAFE_INTEGER; // 9007199254740991
console.log(max +1) // 9007199254740992
console.log(max +2) // 9007199254740992 Something is wrong.
console.log(BigInt(max)+BigInt(1)) 9007199254740992n
console.log(BigInt(max)+BigInt(2)) 9007199254740993n
5.10 Absolute global object globalThis
console.log(globalThis) //window // It is suitable for direct operation in complex environment window
边栏推荐
- MySQL transactions
- 安全测试入门介绍
- UCORE lab7 synchronous mutual exclusion experiment report
- Word macro operation: convert the automatic number in the document into editable text type
- LeetCode#237. Delete nodes in the linked list
- Which version of MySQL does php7 work best with?
- Servlet
- Pedestrian re identification (Reid) - Overview
- How to solve the poor sound quality of Vos?
- 软件测试工作太忙没时间学习怎么办?
猜你喜欢
随机推荐
Jupyter installation and use tutorial
Report on the double computer experiment of scoring system based on 485 bus
Capitalize the title of leetcode simple question
Description of Vos storage space, bandwidth occupation and PPS requirements
MySQL数据库(四)事务和函数
Programmers, how to avoid invalid meetings?
遇到程序员不修改bug时怎么办?我教你
Emqtt distribution cluster and node bridge construction
软件测试行业的未来趋势及规划
The minimum sum of the last four digits of the split digit of leetcode simple problem
Global and Chinese market of goat milk powder 2022-2028: Research Report on technology, participants, trends, market size and share
Word macro operation: convert the automatic number in the document into editable text type
Brief description of compiler optimization level
接口测试面试题及参考答案,轻松拿捏面试官
What are the commonly used SQL statements in software testing?
Lab 8 文件系统
Leetcode notes - dynamic planning -day7
软件测试需求分析之什么是“试纸测试”
安全测试入门介绍
Global and Chinese market for antiviral coatings 2022-2028: Research Report on technology, participants, trends, market size and share