1. 程式人生 > 實用技巧 >ES7-11語法筆記

ES7-11語法筆記

ES7

1、Array.prototype.includes

includes方法用來檢測陣列中是否包含某個元素,返回布林型別值。

indexOf存在返回下標,不存在返回-1。

let fruits = ['apple','banana']
console.log(fruits.includes('apple')) // true
console.log(fruits.includes('strewberry')) // false

2、指數操作符

**實現冪運算,相當於Math.pow

ES8

1.async 和 await

可以讓非同步程式碼像同步程式碼一樣

非同步程式設計解決方案:callback回撥函式,生成器函式generator、Promise、async 和 await

  1. async函式
  • 返回值為Promise物件
  • Promise物件的結果由async函式執行的返回值決定
    • 返回非Promise型別,狀態為resolved
    • 丟擲錯誤,狀態為rejected
    • 返回是Promise型別,狀態為該Promise的狀態
async function fn(){
    return 'a'
}
const result = fn()
console.log(result) // promise物件
  1. await表示式
  • 必須放在async函式中
  • 右側表示式一般為promise物件
  • 返回的是promise成功的
  • await的promise失敗了,就會丟擲異常,需要通過try...catch
    捕獲處理
const p = new Promise((resovle,reject)=>{
    reject('失敗了')
})
async function main(){
    try{
        let result = await p
        console.log(result)
    }catch(e){
        console.log(e) // 失敗了
    }
}
  1. async與await結合讀取檔案內容
const fs = require('fs')

function readFile1(){
    return new Promise((resolve,reject)=>{
        fs.readFile('./file1.txt',(err,data)=>{
            if(err) reject(err)
            resolve(data)
        })
    })
}
function readFile2(){
    return new Promise((resolve,reject)=>{
        fs.readFile('./file2.txt',(err,data)=>{
            if(err) reject(err)
            resolve(data)
        })
    })
}
function readFile3(){
    return new Promise((resolve,reject)=>{
        fs.readFile('./file3.txt',(err,data)=>{
            if(err) reject(err)
            resolve(data)
        })
    })
}
async function main(){
    let file1 = await readFile1()
    let file2 = await readFile2()
    let file3 = await readFile3()
    console.log(file1.toString()) // 檔案1的內容
}
main()
  1. async與await結合傳送Ajax請求
// 傳送ajax請求
function sendAjax(url){
    return new Promise((resolve,reject)=>{
        const xhr = new XMLRequest()
        xhr.open('GET',url)
        xhr.send()
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && x.status < 300){
                    resolve(x.response)
                }else{
                    reject(x.status)
                }
            }
        }
    })
}

async function main(){
    let result = await sendAjax('url')
    console.loog(result)
}

main()

2、物件方法擴充套件

Object.values:獲取物件所有的值

Object.entries:返回陣列 每一個成員又是陣列 第一個元素是鍵 第二個元素是值

Object.getOwnPropertyDescriptors:獲取物件屬性的描述物件

const student={
    name:'xiaoming',
    age:18
}
// keys 獲取物件所有的鍵名
console.log(Object.keys(student)) // [name,age]
// values 獲取物件所有的值
console.log(Object.values(student)) // 0 xiaoming 1 18

// entries 返回陣列 每一個成員又是陣列 第一個元素是鍵 第二個元素是值
console.log(Object.entries(student)) // [[key,value],[key,value]]
// 建立Map
const m = new Map(Object.entries(student))
console.log(m) 

// getOwnPropertyDescriptors 獲取物件屬性的描述物件
// 作用:深層次物件克隆
console.log(Object.getOwnPropertyDescriptors(studnet)) // {name{},age{}}
// 建立物件Object.create(原型物件,描述物件)
const obj = Object.create(null,{
    name:{
        // 設定值
        value:'xiaoming'
        // 屬性特性
        writable:true // 寫
        configurable:true // 刪
        enumerable:true // 編輯
    }
})

ES9

1、擴充套件運算子和rest引數

ES6:針對引數

ES9:物件

// rest引數
function connect(host,port,...user){
    console.log(host) // 127.0.0.1
    console.log(user) // {username:'',password:''}
}
connect({
    host:'127.0.0.1',
    port:3306,
    username:'root',
    password:'root'
})

// 擴充套件運算子
const student1 ={
    name1:'xiaoming'
}
// ...studnet1 => name:'xiaoming'
const student2 ={
    name2:'xiaoli'
}
const student3 ={
    name3:'xiaozhang'
}
const student = {...student1,...student2,...student}
console.log(student) // {name1:'xiaoming',name2:'xiaoli'}

2、正則擴充套件

  1. 命名捕獲分組(?<name>)
let str = '<a href="http://www.atguigu.com">尚矽谷</a>'
// 提取url和標籤文字
const reg = /<a href='(.*)'>(.*)<\/a>/
// 執行
const result = reg.exec(str)
console.log(result) // [匹配的結果,第一個(.*),第二個(.*)]
console.log(result[1]) // http://www.atguigu.com
console.log(result[2]) // 尚矽谷
let str = '<a href="http://www.atguigu.com">尚矽谷</a>'

const reg = /<a href='(?<url>.*)'>(?<text>.*)<\/a>/

const result = reg.exec(str)

console.log(result) // 多了groups內容 groups{url:'',text:''}
  1. 反向斷言
// 正向斷言
let str = 'abc123蘋果456香蕉'
// 根據數字456後面的香蕉,判斷前面是否合法
const reg = /\d+(?=香)/
const result = reg.exec(str)
console.log(result) // 456
// 反向斷言
let str = 'abc123蘋果456香蕉'
// 根據數字前面的蘋果,判斷後面是否合法
const reg = /(?<=果)\d+/
const result = reg.exec(str)
console.log(result) // 123
  1. dotAll模式

.元字元:除換行符以外的任意單個字元

dotAll模式/s

// dotAll以前
// 提取電影名稱和上映時間提取出來
let str = `
	<ul>
		<li>
            <a>肖生克的救贖</a>
            <p>上映日期:1994-89-10</p>
		</li>
		<li>
            <a>阿甘正傳</a>
            <p>上映日期:1994-87-86</p>
		</li>
	</ul>`

//宣告正則
const reg = /<li>\s+<a>(.*?)<\/a>/
//執行匹配
const result = reg.exec(str)
console.log(result) // 肖生克的救贖

//宣告正則
const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/
//執行匹配
const result = reg.exec(str)
console.log(result) // 肖生克的救贖 上映日期:1994-89-10
// .dotAll
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/s
const result = reg.exec(str)
console.log(result) // 肖生克的救贖 上映日期:1994-89-10

const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs
let result
let data = []
while(result = reg.exec(str)){
    console.log(result) // 肖生克的救贖 上映日期:1994-89-10  阿甘正傳 上映日期:1994-87-86
    data.push({title:result[1],time:result[2]})
}
console.log(data) // [{title:'',time:''},{}]

ES10

1、Object.fromEntries

Object.fromEntries二維陣列Map物件轉換為物件

// 二維陣列
const result = Object.fromEntries([
    ['name','xiaoming'],
    ['age',19]
])
console.log(result) //{name:'xiaoming',age:19}

// Map物件
const m = new Map()
m.set('name','xiaoming')
const result = Object.fromEntries(m)
console.log(result) //{name:'xiaoming'}

ES8:Object.entries將一個物件轉換為二維陣列

const arr = Object.entries({
    name:'xiaoming'
})
console.log(arr) // [[name,'xiaoming']]

2、字串擴充套件方法trimStart和trimEnd

trimStart:清除字串左側空白

trimEnd:清除字串右側空白

3、陣列擴充套件方法flat和flatMap

flat:將一個多維陣列轉化為低維陣列

flatMap:map+flat,map的結果是多維陣列的可以返回低維陣列

// flat 
// 二維->一維
const arr = [1,2,3,[4,5,6]]
console.log(arr.flat()) // [1,2,3,4,5,6]

// flat(n) n表示深度
// 三維->一維
const arr = [1,2,3,[4,5,6,[7,8,9]]]
console.log(arr.flat(2)) // [1,2,3,4,5,6,7,8,9]
// map
const arr = [1,2,3,4]
const result = arr.map(item => [item * 10])
console.log(result) // [[10],[20],[30],[40]]

// flatMap
const arr = [1,2,3,4]
const result = arr.flatMap(item => [item * 10])
console.log(result) // [10,20,30,40]

4、Symbol.prototype.description

description:獲取Symbol的描述字串

let s = Symbol('apple')
console.log(s.description) // apple

ES11

1、私有屬性

class Person{
    // 公有屬性
    name;
    // 私有屬性
    #age;
    #weight;
    // 構造方法
    constructor(name,age,weight){
        this.name = name
        this.#age = age
        this.#weight = weight
    }
	intro(){
        console.log(this.#age)
    }
}

const girl = new Person('xiaohong',18,'45kg')

console.log(gril) //Person{name:'xiaohong',age:18,weight:'45kg'}

console.log(gril.#age) // SyntaxError Private field #age must be declard in an enclosing class
  
girl.intro() // 18 

2、Promise.allSettled

接收Promise的陣列

返回Promise物件。狀態永遠為成功,值是Promise陣列中的結果和結果狀態

const p1 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('商品資料-1')
    },1000)
})
const p2 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('商品資料-2')
    },1000)
})

// allSettled
const result = Promise.allSettled([p1,p2])
console.log(reslut) // resovled [{},{}]

// all 狀態:傳入引數都成功才成功 
// 有一個rejected,狀態為rejected,值為出錯Promise的值
// 都resolved,狀態為resolved,值為成功的Promise的陣列
const result Promise.all([p1,p2])

3、String.prototype.mathAll

得到正則批量匹配的結果

// 提取電影名稱和上映時間提取出來
let str = `
	<ul>
		<li>
            <a>肖生克的救贖</a>
            <p>上映日期:1994-89-10</p>
		</li>
		<li>
            <a>阿甘正傳</a>
            <p>上映日期:1994-87-86</p>
		</li>
	</ul>`

//宣告正則
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
const result = str.matchAll(reg)
console.log(result) // 可迭代物件 存在next()方法

for (let v of result){
    console.log(v)// 肖生克的救贖 上映日期:1994-89-10  阿甘正傳 上映日期:1994-87-86
}

const arr = [...reslut]
console.log(arr) // []

4、可選鏈操作符

?.:物件型別的引數深度深

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'
	}
})

5、動態import

按需載入

const btn = document.getElementById('btn')
btn.onclick = function(){
    import('./hello.js').then(module => {
        module.hello()
    })
}

6、BigInt型別

n:大數值運算

let n = 123n;
console.log(n, typeof(n))// 123n bigint

let n = 123
console.log(BigInt(n)) // 123n
console.log(BigInt(1.2)) // RangeError 報錯

let max = Number.MAX_SAFF_INTEGER
console.log(max + 1) // +1
console.log(max + 2) // +1

console.log(BigInt(max)+1)// 報錯
console.log(BigInt(max) + BigInt(1)) // +1
console.log(BigInt(max) + BigInt(2)) // +2

7、絕對全域性物件globalThis

忽略環境,始終指向全域性物件

console.log(globbalThis) // window