ES7-ES11
210429
1、ECMAScript7新特性
1.1. Array.prototype.includes
includes方法用来检测数组中是否包含某个元素,返回布尔类型值
//indexOf 返回0 1
const famousbook = [‘西游记‘,‘红楼梦‘,‘三国演义‘,‘水浒传‘]
console.log(famousbook.includes(‘西游记‘)) //true
console.log(famousbook.includes(‘撒哈拉沙漠‘)) //false
1.2. 指数操作符
在ES7中引入指数运算符**
,用来实现幂运算,功能与Math.pow结果相同
console.log(2 ** 10)
console.log(Math.pow(2,10))
2、ECMAScript8新特性
2.1 async和await
async和await两种语法结合可以让异步代码像同步代码一样
async函数
- 返回值为promise对象
- promise对象的结果由async函数执行的返回值决定
async function fn(){
//返回的结果不是一个promise类型的对象,返回的结果就是成功promise对象
//return 字符串 return;
//抛出错误,返回的结果是一个失败的promise
//throw new Error(‘出错啦!‘)
//返回的结果如果是一个promise对象,fn()根据promise对象的状态返回
return new Promise((resolve,reject)=>{
resolve(‘成功的数据‘)
reject(‘失败的错误‘)
})
}
const res = fn()
//console.log(res)
//调用then方法
result.then(value => {
console.log(value)
},reason => {
console.warn(reason)
})
await表达式
- await必须写在async函数中
- await右侧的表达式一般为promise对象
- await返回的是promise成功的值
- await的promise失败了,就会抛出异常,需要通过try...catch捕获处理
const p = new Promise((resolve,reject)=>{
//resolve("user data")
reject("error")
})
//await要放在async函数中
async function main(){
try{
let res = await p
console.log(res) //user data
}catch(e){
console.log(e) //error
}
}
//调用函数
main()
async和await结合读取文件
const fs = require(‘fs‘)
function file1(){
return new Promise((resolve,reject)=>{
fs.readFile("文件路径",(err,data)=>{
if(err)
reject(err)
resolve(data)
})
})
}
async function fn(){
//获取file1内容
let f1 = await file1()
//输出文件中的内容
console.log(f1.toString())
}
async和await封装AJAX请求
需解决同源策略
<script>
function sendAJAX(url) {
return new Promise((resolve, reject) => {
const x = new XMLHttpRequest()
x.open(‘GET‘, url)
x.send()
x.onreadystatechange = function () {
if (x.readyState === 4)
if (x.status >= 200 && x.status < 300) {
resolve(x.response)
} else {
reject(x.status)
}
}
})
}
//promise then方法测试
// sendAJAX("http://api.apiopen.top/getJoke").then(value => {
// console.log(value)
// }, reason => {})
// async与await测试
async function fn(){
let res = await sendAJAX("http://api.apiopen.top/getJoke")
let res2 = await sendAJAX("https://joke-api-strict-cors.appspot.com/jokes/random")
console.log(res)
console.log(res2)
}
fn()
</script>
2.2 Object.values 和 Object.entries
0509
- Object.values()方法返回一个给定对象的所有可枚举属性值的数组
- Object.entries()方法返回一个给定对象自身可遍历属性[key,value]的数组
<script>
const school = {
name:"phy",
city:[‘changsha‘,‘beijing‘,‘shanghai‘],
object:[‘前端‘,‘c‘]
}
//获取对象所有的键
console.log(Object.keys(school))
//获取对象所有的值
console.log(Object.values(school))
// entries 返回一个数组
console.log(Object.entries(school))
const m = new Map(Object.entries(school))
console.log(m.get(‘city‘))
</script>
2.3 Object.getOwnPropertyDescriptors
该方法返回指定对象所在自身属性的描述对象
<script>
//对象属性的描述对象
console.log(Object.getOwnPropertyDescriptors(school))
// 进行深层次对象的拷贝
const obj = Object.create(null,{
name:{
// 设置值
value:‘phy‘,
// 属性特性
writable:true,
configurable:true,
enumerable:true
}
})
console.log(Object.getOwnPropertyDescriptors(obj))
</script>
3、ECMAScript9新特性
3.1 扩展运算符和rest参数
Rest参数与spread扩展运算符在ES6中已引入,不过ES6中只针对数组,在ES9中为对象提供了像数组一样的rest参数和扩展运算符
<script>
function connect({host,port,...user}){
console.log(host); //127.0.0.1
console.log(port); //3306
console.log(user); //{username: "root", password: "root", type: "master"}
}
connect({
host: ‘127.0.0.1‘,
port: 3306,
username: ‘root‘,
password: ‘root‘,
type: ‘master‘
})
const t = {
ts : ‘唐僧‘
}
const w = {
swk : ‘孙悟空‘
}
const z = {
zbj : ‘猪八戒‘
}
const s = {
ss : ‘沙僧‘
}
const xiyou = {...t,...w,...z,...s} //对象的合并
console.log(xiyou) //{ts: "唐僧", swk: "孙悟空", zbj: "猪八戒", ss: "沙僧"}
</script>
3.2 正则扩展-命名捕获分组
<script>
let str = ‘<a href="http://www.baidu.com">百度</a>‘
//提取url与标签文本
const reg = /<a href="(.*)">(.*)<\/a>/
//执行
const result = reg.exec(str)
console.log(result)
console.log(result[1])
console.log(result[2])
//es9 ?<命名>
let str = ‘<a href="http://www.baidu.com">百度</a>‘
//对捕获的结果添加一个属性
const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/
const result = reg.exec(str)
//group中有变化
console.log(result)
console.log(result.groups.url)
console.log(result.groups.text)
</script>
3.3 正则扩展-反向断言
<script>
// 正则断言
let str = ‘jdsjiojiowdjc呵68900啦‘
// 正向断言
const reg = /\d+(?=啦)/
const res = reg.exec(str)
// 反向断言
const reg = /(?<=呵)\d+/
const res = reg.exec(str)
console.log(res)
</script>
3.4 正则dotAll模式
<script>
//dot . 元字符 除换行符以外的任意单个字符
let strHtml = `
<ul>
<li>
<a>肖生克的救赎</a>
<p>上映时间:1994-09-10</p>
</li>
<li>
<a>驯龙高手</a>
<p>上映时间:2014-09-10</p>
</li>
</ul>`
//声明正则
//匹配一个空白字符,包括空格、制表符、换页符和换行符
//const regh = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/
// const resh = regh.exec(strHtml)
// console.log(resh)
//es9
//加了s后的.可以匹配任意字符(包括换行符) g全局匹配
const regh = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs
let resh;
let data = [];
while(resh = regh.exec(strHtml)){
data.push({title:resh[1],time:resh[2]})
}
console.log(data) //0: {title: "肖生克的救赎", time: "上映时间:1994-09-10"}
//1: {title: "驯龙高手", time: "上映时间:2014-09-10"}
</script>
4、ECMAScript10新特性
4.1 对象扩展方法Object.fromEntries
Object.fromEntries:将数组/Map转为对象
<script>
//Object.fromEntries
//将数组转化成对象
//二维数组
const result = Object.fromEntries([
[‘name‘,‘phy‘],
[‘address‘,‘changsha‘,‘shanghai‘,‘wuhan‘]
])
console.log(result)
//Map
const m = new Map()
m.set(‘name‘,‘hhhhh‘)
const res = Object.fromEntries(m)
console.log(res)
//Object.entries ES8
//将对象转数组
const arr = Object.entries({
name: ‘hcsuih‘
})
console.log(arr)
</script>
4.2 字符串扩展方法trimStart/trimEnd
trimStart清除左侧空格
trimEnd清除右侧空格
<script>
let str = ‘ hduhscduiis ‘
console.log(str.trimStart())
console.log(str.trimEnd())
</script>
4.3 数组扩展方法flat/flatMap
<script>
//将多维数组转化为低维数组
//flat
const arr = [1,2,3,4,[5,6]]
console.log(arr.flat()) //[1, 2, 3, 4, 5, 6]
const arr2 = [1,2,3,4,[5,6,[7,8,9]]]
//参数为深度 是一个数字
console.log(arr2.flat()) //[1, 2, 3, 4, 5, 6, Array(3)]
console.log(arr.flat(2)) //[1, 2, 3, 4, 5, 6, 7, 8, 9]
//flatMap
const arr3 = [1,2,3,4,5]
const res = arr3.map(item => item * 10)
const res2 = arr3.map(item => [item * 10])
const res3 = arr3.flatMap(item => [item * 10])
console.log(res) //[10, 20, 30, 40, 50]
console.log(res2) //[Array(1), Array(1), Array(1), Array(1), Array(1)]
console.log(res3) //[10, 20, 30, 40, 50]
</script>
4.4 symbol扩展
Symbol.prototype.description
<script>
let s = Symbol(‘PHY‘)
console.log(s.description) //PHY
</script>
5、ECMAScript11新特性
5.1 私有属性
<script>
//私有属性
class Person{
// 公有属性
name
// 私有属性
#age
#weight
// 构造方法
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)
}
}
const g = new Person(‘disjc‘,18,‘50kg‘)
g.intro()
//报错
// console.log(g.name)
// console.log(g.#age) //Private field ‘#age‘ must be declared in an enclosing class
// console.log(g.#weight)
</script>
5.2 Promise.allSettled
allSettled无论数组中的promise成功还是失败都会全部执行
all数组里有reject停止执行
<script>
const p1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(‘商品数据-1‘)
},1000)
})
const p2 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(‘商品数据-2‘)
reject(‘出错了‘)
},1000)
})
//调用allSettled方法
const res = Promise.allSettled([p1,p2])
//all
const res = Promise.all([p1,p2])
console.log(res)
</script>
5.3 String.prototype.matchAll
批量提取数据
<script>
let str = `
<ul>
<li>
<a>肖生克的救赎</a>
<p>上映时间:1994-09-10</p>
</li>
<li>
<a>驯龙高手</a>
<p>上映时间:2014-09-10</p>
</li>
</ul>`
//.*?禁止贪婪 s模式修正符dotAll g全局匹配
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
const res = str.matchAll(reg)
//for(let v of res)
// console.log(v)
//从页面中提取数据很方便
const arr = [...result]
console.log(arr)
</script>
5.4 可选链操作符
?.
<script>
//?.
function main(config){
//&&->两边结果均为true时,返回右边的值
//一个一个判断,存在输出该值,不存在报错
//const dbHost = config && config.db && config.db.host
//判断不存在返回undefined,不报错
const dbHost = config?.db?.host
console.log(dbHost)
}
main({
db: {
host:‘192.168.1.100‘
username:‘root‘
},
cache: {
host:‘192.168.1.200‘
username:‘admin‘
}
})
</script>
5.5 动态import
<button id="btn">
点击
</button>
<script src="./app.js" type="module">
//按需加载
</script>
//app.js
//静态导入
//import * as m1 from "./hello.js"
const btn = document.getElementById(‘btn‘)
btn.onclick = function(){
//动态引入,需要用再加载
import(‘./hello.js‘).then(module=>{
//console.log(module)
module.hello()
})
}
//hello.js
export function hello(){
alert(‘Hello‘)
}
5.6 BigInt
大整型
<script>
let n = 521n
console.log(n,typeof(n)) //521n bigint
//函数
let n = 123
//不能传浮点型
console.log(BigInt(n))
//大数值运算
let max = Number.MAX_SAFE_INTEGER
console.log(max)
console.log(max+1)
console.log(max+2)
console.log(BigInt(max))
console.log(BigInt(max)+BigInt(1))
console.log(BigInt(max)+BigInt(2))
</script>
5.7 globalThis
始终指向全局对象
<script>
//node.js中也支持
console.log(globalThis)
</script>