当前位置:网站首页>[ecmascript6] other new interface features
[ecmascript6] other new interface features
2022-07-28 14:22:00 【Willard Leozi】
One 、ECMAScript7 New characteristics
1.1 Array.prototype.includes
const mingzhu = [' Journey to the west ',' A dream of red mansions ',' The romance of The Three Kingdoms ',' Water margin '];
// Judge
console.log(mingzhu.includes(' Journey to the west ')); // true
console.log(mingzhu.includes('123')); // false
console.log(mingzhu.indexOf(' A dream of red mansions ')); // 1
console.log(mingzhu.indexOf('123')); // -1
Array of includes Method returns whether it contains the element , Return if included true, If not, return false. and indexOf The method is to determine the position of the element in the array , If the element exists in the array , Returns the location index , Otherwise return to -1.
1.2 Exponential operators
console.log(2 ** 10); // 1024
console.log(Math.pow(2, 10)); // 1024
use ** Instead of Math.pow Perform index operation .
Two 、ECMAScript8 New characteristics
2.1 Object.values and Object.entries
// Declare objects
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
console.log(Object.entries(school));
// establish Map
const m = new Map(Object.entries(school));
console.log(m.get('cities'));

It should be noted that ,entries Method returns an array , And each member is also an array .
2.2 Object.getOwnPropertyDescriptors
adopt Object.create You can create an object , And make some restrictions on the internal attributes of the object .
const obj = Object.create(null, {
// The prototype object is set to null
name: {
// Set the value
value: ' Silicon Valley ', // name The value of the property
// Attribute characteristics
writable: true, // This property is writable
configurable: true, // This attribute can be deleted
enumerable: true // This attribute can be enumerated
}
});
const school = {
name:" Silicon Valley ",
cities:[' Beijing ',' Shanghai ',' Shenzhen '],
xueke: [' front end ','Java',' big data ',' Operation and maintenance ']
};
console.log(Object.getOwnPropertyDescriptors(school));

3、 ... and 、ECMAScript9 New characteristics
3.1 Rest/Spread attribute
Rest Parameters and spread The extension operator is in ES6 Has introduced , however ES6 For arrays only , stay ES9 Provides an array like for objects rest Parameters and extension operators .
//rest Parameters
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'
});
// Object to merge
const skillOne = {
q: ' Tianyinbo '
}
const skillTwo = {
w: ' magic ability to sustain the thrusts of sharp weapons on one's bare skin '
}
const skillThree = {
e: ' The thunder broke '
}
const skillFour = {
r: ' The Dragon wags its tail '
}
const mangseng = {
...skillOne, ...skillTwo, ...skillThree, ...skillFour};
console.log(mangseng)

3.2 Regular expression names capture group
demand : extract str Medium url And label text
1. Traditional way of implementation :
let str = '<a href="http://www.atguigu.com"> Silicon Valley </a>';
const reg = /<a href="(.*)">(.*)<\/a>/;
const result = reg.exec(str);
console.log(result);
console.log(result[1]);
console.log(result[2]);

2. How to name the capture Group :
let str = '<a href="http://www.atguigu.com"> Silicon Valley </a>';
const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result = reg.exec(str);
console.log(result.groups.url);
console.log(result.groups.text);

3.3 Regular expression reverse assertion
Interpretation of assertions : Judge whether the matching result is correct
demand : matching str The second number in , Here is 555
let str = 'JS5211314 Do you know? 555 La la la ';
// A positive assertion
const reg = /\d+(?= La )/;
const result = reg.exec(str);
console.log(result);
// Reverse assertion
const reg1 = /(?<= Well )\d+/;
const result1 = reg.exec(str);
console.log(result1);

3.4 Regular expressions dotAll Pattern
dot It refers to symbols . : It is a metacharacter in regular expressions , Used to match any single character except newline
<ul>
<li>
<a> Shawshank's salvation </a>
<p> Release date : 1994-09-10</p>
</li>
<li>
<a> Forrest gump </a>
<p> Release date : 1994-07-06</p>
</li>
</ul>
demand : Through regular expressions, the above html The movie name and release time in the code are extracted
1. The traditional way
let str = ` <ul> <li> <a> Shawshank's salvation </a> <p> Release date : 1994-09-10</p> </li> <li> <a> Forrest gump </a> <p> Release date : 1994-07-06</p> </li> </ul>`;
const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/;
const result = reg.exec(str);
console.log(result);

2.dotAll The way
let str = ` <ul> <li> <a> Shawshank's salvation </a> <p> Release date : 1994-09-10</p> </li> <li> <a> Forrest gump </a> <p> Release date : 1994-07-06</p> </li> </ul>`;
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
let result;
let data = [];
while(result = reg.exec(str)){
data.push({
title: result[1], time: result[2]});
}
console.log(data);

Four 、ECMAScript10 New characteristics
4.1 Object.fromEntries
Object.fromEntries Receive a binary array or Map, To create an object , Execution and entries Reverse operation .
// Two dimensional array
const result = Object.fromEntries([
['name',' Silicon Valley '],
['xueke', 'Java, big data , front end , Cloud computing ']
]);
console.log(result)
//Map
const m = new Map();
m.set('name','ATGUIGU');
const result1 = Object.fromEntries(m);
console.log(result1)

review entries Usage of , Is to traverse the keys and values in an object .
const arr = Object.entries({
name: " Silicon Valley "
})
console.log(arr);

4.2 trimStart and trimEnd
let str = ' iloveyou ';
console.log(str);
console.log(str.trimStart());
console.log(str.trimEnd());

4.3 Array.prototype.flat and flatMap
//flat flat : Convert multidimensional array to low order array
const arr = [1,2,3,4,[5,6]];
const arr1 = [1,2,3,4,[5,6,[7,8,9]]];
// The parameter is depth , It's a number , If you don't fill in the silent opinion 1
console.log(arr.flat());
console.log(arr1.flat(2));
//flatMap
const arr3 = [1,2,3,4];
const result = arr3.flatMap(item => [item * 10]);
console.log(result);

4.4 Symbol.prototype.description
let s = Symbol(' Silicon Valley ');
console.log(s.description); // Silicon Valley
5、 ... and 、ECMAScript11 New characteristics
5.1 String.prototype.matchAll
let str = `<ul> <li> <a> Shawshank's salvation </a> <p> Release date : 1994-09-10</p> </li> <li> <a> Forrest gump </a> <p> Release date : 1994-07-06</p> </li> </ul>`;
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
const result = str.matchAll(reg);
// for(let v of result){
// console.log(v);
// }
const arr = [...result];
console.log(arr);

5.2 Private properties of class
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(' Xiaohong ', 18, '45kg');
console.log(girl.name);
// console.log(girl.#age); // Report errors Because the private attribute cannot be read
// console.log(girl.#weight); // Report errors Because the private attribute cannot be read
girl.intro();

5.3 Promise.allSettled And Promise.all
const p1 = new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(' Commodity data - 1')
// reject(' Something went wrong ')
},1000)
})
const p2 = new Promise((resolve, reject)=>{
setTimeout(()=>{
// resolve(' Commodity data - 2')
reject(' Error !')
},1000)
})
// call allsettled Method
const result = Promise.allSettled([p1, p2])
console.log(result)
const res = Promise.all([p1, p2]);
console.log(res)

Whether it's allSettled still all The method is to receive a group Promise Parameters , Their return values are all Promise object , But there are still differences , about allSettled methods , No matter what Promise How about the parameters , Its return value Promise The status is always success , about all methods , Only when all parameters Promise When you are successful , Its state is successful , Otherwise, they will all fail .
5.4 Optional chain operator
Optional chain operator :?.
function main(config){
// const dbHost = config && config.db && config.db.host;
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'
}
})
In the above code, the optional chain operator ?. Replace the traditional existence judgment of objects and attributes .
const dbHost = config?.db?.host; Equivalent to const dbHost = config && config.db && config.db.host;
5.5 dynamic import Import
dynamic import Import : Resources can be loaded on demand , So as to optimize the project
app.js file :
const btn = document.getElementById('btn');
btn.onclick = function(){
import('./hello.js').then(module => {
module.hello();
});
}
html file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> dynamic import </title>
</head>
<body>
<button id="btn"> Click on </button>
<script src="./js/app.js" type="module"></script>
</body>
</html>
边栏推荐
猜你喜欢

开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能

论文研读--Masked Generative Distillation

LeetCode 0143. 重排链表

Security assurance is based on software life cycle -istio authorization mechanism

Solve the problem that uniapp wechat applet canvas cannot introduce fonts

Metersphere -- Open Source continuous testing platform

Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
![[ecmascript6] set and map](/img/64/dd6ffc5f0faf881b990e609cf62343.png)
[ecmascript6] set and map

如何有效进行回顾会议(上)?

Security assurance is based on software life cycle -istio authentication mechanism
随机推荐
As a programmer, how to manage time efficiently?
Clickhouse distributed cluster construction
基于NoneBot2的qq机器人配置记录
如何有效进行回顾会议(上)?
Verification code brute force cracking test [easy to understand]
[utils] fastdfs tool class
手机滚动截屏软件推荐
这3款在线PS工具,得试试
[lvgl events] event code
Target detection: speed and accuracy comparison (fater r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)
Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱
83. (cesium home) how the cesium example works
【Utils】CookieUtil
Custom Configuration Sections
Master several common sorting - Select Sorting
聊天室功能的实现
Super resolution reconstruction based on deep learning
QT self-made soft keyboard is the most perfect and simple, just like its own virtual keyboard
Three methods to disassemble the rotation array
7.27 simulation summary