当前位置:网站首页>ES6 knowledge points
ES6 knowledge points
2022-06-25 17:08:00 【Dongdong Dongdong】
let And const
let、const Relative to var Of characteristic :
- Named variables have no variable promotion .
- The role of block level scope , Variables cannot be accessed outside the block .
- Cannot repeat declaration .
and const There is an additional feature that cannot be modified .
== Be careful const With the object :== use const To declare an object , Objects cannot be modified directly , But you can modify the properties in the object .
Template string
Template string = The quotation marks + ${} Indicates the variable .
You do not need to use... When splicing strings and variables + To divide , You just need to use... For variables ${} Just round it up .
Function parameter defaults
ES6 You can assign a default value to a parameter when the calling function does not give a parameter .
Parameter default It can be Specific parameters perhaps function .
// Specific parameters
function add(a = 10, b = 20){
return a + b;
}
add(); //30
add(20); //40
// function
function add(a = 10, b = getVal(5)){
return a + b;
}
function getVal(c){
return c + 5;
}
add(); //20
… -> Formal parameter remainder / Argument expansion
Function remaining parameter characters
You can use... In the formal parameters of a function …xxx Form to receive extra parameters in arguments , What you get is a that stores redundant parameters Real array xxx.
function test(a, ...k){
console.log(k)
}
test(10,20,"hello"); //[20, 'hello']
Function extension operator
Using the extension operator in the arguments of a function can The items of the array As Separate Pass arguments to the function .
const arr = [10,20,30,40];
console.log(Math.max(...arr)); //40
Arrow function
Arrow function writing :
let fn = () => {
}
//() Fill in the parameters
//{} Is the function content
this Point to :
// stay ES5 Function ,this Refers to the context in which the function is called .
// stay ES6 In the arrow function ,this It points to the scope chain in the code .
Deconstruct assignment
The purpose of deconstruction assignment is to get the object at one time / Multiple attributes of an array .
Follow the format : let {} = {} or let [] = [];
Object to deconstruct : Deconstruct an attribute with the same attribute name
// The same attribute name is required
let a = {
b: 10,
c: 20
}
let {
c,b,d} = a;
console.log(c,b,d) //20 10 undefined
An array of deconstruction :
let a = [10,20,30];
let [b,c,d] = a;
console.log(b,c,d); //10 20 30
Object shorthand
When defining objects ,
- If an existing variable is used for an internal attribute, it can be abbreviated to .
- Function shorthand can omit keywords .
let name = 'jack'
let obj = {
name, // be relative to ES5 Of name: name;
sayHi(){
} // be relative to ES5 Of sayHi: function(){}
}
Object addition method
Object.is() Judge whether two things are strictly equal .
Object.assign() Merge objects , Is a shallow copy .
Set data type
Set Express Sets that do not duplicate .
// Definition
let set = new Set();
// add to
set.add(2); //Set(1) {2}
set.add("4"); //Set(2) {2, '4'}
set.add("4"); //Set(2) {2, '4'}
// Delete
set.delete(2); //Set(1) {'4'}
// lookup
set.has('4'); //true
// length
set.size //1
Map data type
Map Is a list of key value pairs .
let map = new Map()
map.set('name','zhangsan')
console.log(map) //Map(1) {'name' => 'zhangsan'}
iterator
Iterators are a new traversal mechanism , Is used to traverse the data structure The pointer , It can record the traversal position .
First there is a data structure , To generate its iterators .
// Generate iterators
const items = ['one','two']
const ite = items[Symbol.iterator]();
Using the iterator once at a time next() Method , will Get a data , then The pointer moves down .
// iterator.next()
console.log(ite.next()); //{value: 'one', done: false}
console.log(ite.next()); //{value: 'two', done: false}
console.log(ite.next()); //{value: undefined, done: true}
generator
generator function , The return value after running is a generator .
The generator uses next() The function does not run until the next breakpoint .
// The function is named in function It is marked with *
function* gogo(){
console.log('start')
yield 2
console.log('still')
yield 3
console.log('more')
//yield Only in generator Use in a function
}
let fn = gogo()
fn.next() //start {value: 2, done: false}
fn.next() //still {value: 3, done: false}
fn.next() //more {value: undefined, done: true}
promise
promise There are three states :
The first state is pending( That is, when the constructor performs an asynchronous operation ).
The second state is resolved, Get a successful result .
The third state is rejected, Get the result of failure .
promise Constructors :
Parameters : Its argument is a function of two (resolved,rejected) Is a function of parameters . At the same time, the asynchronous operation is also performed in this function .
Return value : It's a promise object , This object contains then() function .
promise object :
- promise Object has methods then():then The arguments to the function are also two functions , Corresponding reception resolved,rejected The value that the function receives .
- then() The return value of is also a promise object .
- promise Objects also have methods catch( (error) => {} ) Equivalent to then( null, (err) => {} ), That is, the method used to predict errors and capture or only need error information .
Preliminary simulation promise operation :
let pm = new Promise((resolved,rejected) => {
// Suppose the data returned by the backend
let res = {
code: 200, //201
data: {
msg: ' succeed '
},
error: {
msg: ' failed '
}
}
// Suppose asynchronous operation
setTimeout(() => {
if(res.code === 200){
resolved(res.data)
}else{
rejected(res.error)
}
})
})
// Get the return result of the above asynchronous operation
pm.then((val) => {
console.log(val)
}, (err) => {
console.log(err)
})
// result
// res.code = 200 when ,{msg: ' succeed '}
// res.code = 201 when ,{msg: ' failed '}
Upgraded simulation promise operation :
// take promise Object as the return value of the function
function timeOut(ms){
return new Promise((resolved,rejected) => {
setTimeout(() => {
resolved('promise success')
}, ms)
})
}
timeOut(2000).then((val) => {
console.log(val)
})
promise simulation ajax
// contrast
// var xhr = new XMLHttpRequest();
// xhr.open('GET', 'http://suggest.taobao.com/sug?code=utf-8&q= Product keywords &callback=cb');
// xhr.responseType = 'json'
// xhr.setRequestHeader('Accept', 'application/json')
// xhr.send();
// xhr.onreadystatechange = function() {
// if (xhr.readyState == 4 && xhr.status == 200) {
// console.log(xhr.responseText);
// } else {
// console.log(xhr.statusText);
// }
// };
//promise encapsulation
function getJSON(url) {
return new Promise((resolved, rejected) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url);
xhr.responseType = 'json'
xhr.setRequestHeader('Accept', 'application/json')
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
resolved(xhr.response);
} else {
rejected(xhr.statusText);
}
};
})
}
getJSON('https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976')
.then((data) => {
console.log(data)
}, (err) => {
console.log(err)
})
Promise Other methods of object
all() Method : Let more than one promise Objects perform asynchronous operations in parallel .
let promise1 = new Promise(() => {
})
let promise2 = new Promise(() => {
})
let promise3 = new Promise(() => {
})
let p4 = Promise.all([promise1, promise2, promise3])
p4.then(() => {
// Only three are successful
}).catch(err => {
// One out of three fails
})
race() Method : Set the maximum time for the request , If the time limit is exceeded, an error will be returned .
async
async Is based on promise The asynchronous solution for , And because of promise, Easy to read and operate .
Basic use : Add before function async keyword ,async The function returns one promise object
async function f(){
}
await:
await The order can only be in async Use in a function .
After using async Function return promise Object use then() You can only wait for all... In the function await Call... After the command is executed .
async Subsequent commands in the function must wait await complete
async Subsequent commands outside the function do not have to wait await complete
ES6 modularization
General exposure / Import :
- When defining variables, use
exportExposure data . - Other modules import data
// one module
export xxx
// other module
import {
xxx, xxx, xxx } from module
Example :
// a.js
export let name = 'jack'
export function sayHi(){
}
// b.js
import {
name, sayHi } from './a.js'
Import all the data exposed by one module at a time :
// grammar
import * as xxx from module
// Example
import * as a from './a.js'
console.log(a.name)
a.sayHi()
Default exposure :( Three methods )
- Each module can only be used once , Each module can have a variable 、 Functions or classes are exposed as default values .
// 1. It is exposed when it is defined
export default function(){
console.log(' Method 1 The exposed function is the default ');
}
// 2. Define before expose
let name = 'doug';
export default name;
// 3. Use this value as as Name it default expose
class Student{
// ... }
export {
Student as default};
- The syntax of importing default values is slightly different from that of importing non default values . Import the default values exposed by a module , It's not necessary
{}To the parcel , And don't useasKeyword to rename the default value : For example, import the name, And rename it to familyName
import familyName from './a.js';
Syntax for importing both default and non default values :
import The default value is {
Non default value } from './a.js';
ES6 convert to ES5
babel:ES6 The compiler , Can be ES6 The code is converted to ES5 Code for , So that browsers can get support .
边栏推荐
- TCP聊天+传输文件服务器服务器套接字v2.8 - 修复已知程序4个问题
- [micro service sentinel] overview of flow control rules | detailed explanation of flow control mode for source | < direct link >
- Wechat official account server configuration
- Why does MySQL limit affect performance?
- Good fat man takes you to learn Flink series -flink source code analysis episode I standalone startup script analysis
- Tasklet API usage
- How do components communicate
- internship:Swagger下注解的涉及 接口的提供
- 【精通高并发】深入理解汇编语言基础
- 3年,我是如何涨薪到20k?
猜你喜欢

How to talk about salary correctly in software testing interview

旧手机变废为宝,充当服务器使用

How did I get a salary increase of 13k+ after one year of employment?

How smart PLC constructs ALT instruction

Kalman time series prediction

Notes: lbcf: a Large Scale budget Constrained causal Forest Algorithm

JVM內存結構

Which is better for intermediate and advanced soft exam?

Babbitt yuan universe daily recommendation: three players holding "tens of millions" of collections have revealed the "three routines" of the digital collection market

STM32硬件错误HardFault_Handler的处理方法
随机推荐
这些老系统代码,是猪写的么?
ddia数据密集型应用系统设计 整理
try with resource
Why are there few embedded system designers in the soft test?
数据搬迁最佳实践之使用CDM搬迁线下MySQL到DWS
mac php多版本管理以及安装swoole扩展
效应与定律
mysql使用过程中遇到的问题
3年,我是如何涨薪到20k?
2022云的世界会更好吗
The problem of missing precision of kettle table input components
Kalman time series prediction
剑指 Offer 39. 数组中出现次数超过一半的数字
巴比特 | 元宇宙每日荐读:三位手握“价值千万”藏品的玩家,揭秘数字藏品市场“三大套路”...
【剑指 Offer II 091. 粉刷房子】
JVM內存結構
Structure de la mémoire JVM
redis 分布式锁整理
TCP chat + transfer file server server socket v2.8 - fix 4 known problems
3. conditional probability and independence