当前位置:网站首页>[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>
边栏推荐
猜你喜欢

用友BIP CRM新品发布,赋能大中型企业营销增长

软件测试工程师的职业规划

2022高处安装、维护、拆除考试题库及在线模拟考试

深度学习基础----GNN谱域和空域 (不断完善更新积累)

MeterSphere--开源持续测试平台
![[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks](/img/23/4d07adcb5fb2c3b4c5090dacd02c89.jpg)
[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks

MySQL development skills - View

阿里、京东、抖音:把云推向产业心脏

解决uniapp微信小程序canvas不能引入字体的问题

Mobile phone scrolling screenshot software recommendation
随机推荐
Solve the problem that uniapp wechat applet canvas cannot introduce fonts
Collaborative office tools: Online whiteboard is in its infancy, and online design has become a red sea
Target detection: speed and accuracy comparison (fater r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)
Security assurance is based on software life cycle -istio authorization mechanism
Thrift 序列化协议浅析
每日一题——奖学金
AFNetworking速成教程
QT self-made soft keyboard is the most perfect and simple, just like its own virtual keyboard
Literature reading (245) roller
Super resolution reconstruction based on deep learning
Clickhouse architecture and design
Read how to deploy highly available k3s with external database
在centos中安装mysql5.7.36
【LeetCode】1331. 数组序号转换
Detailed explanation of C language student achievement management system [easy to understand]
HCIP第十一天
Websocket chat
修订版 | 目标检测:速度和准确性比较(Faster R-CNN,R-FCN,SSD,FPN,RetinaNet和YOLOv3)...
【翻译】盐业公司来Linkerd公司是为了负载平衡,留下来是为了效率、可靠性和性能。...
RSA encrypts data with private key and decrypts data with public key (not a signature verification process)