js基础复习(六)

159 阅读4分钟

1. ES7

1.1 includes 数组中如何判断元素是否存在

let arr = [2, 4, 66] 
arr.includes(2) // true
arr.includes(3) // false

2.2 pow 乘方

之前的做法

Math.pow(2, 3) // 2的3次放 8

ES7

console.log(2 ** 5) // 2的5次方

2. ES8

2.1 Async Await

将异步书写形式变成同步的方法。

async function test () {
    let promise = new Promise((resolve) => {
        setTimeout(() => {
            resolve('done')
        }, 1000)
    })
    await promise
    console.log(2) // 会等promise返回后打印
}
test()

2.2 Object keys.values.entries

let obj = {
    x: 1,
    y: 2,
    z: 3
}

Object.keys(obj) // ["x", "y", "z"]
Object.values(obj) // [1, 2, 3]
Object.entries(obj) // [["x", 1], ["y", 2], ["z", 3]]

2.3 对String补白的方式

2.3.1 padStart 从前面补

例子:字符串要3位,不够补足0

for (let i = 0; i < 320; i += 10) {
    console.log(i.toString().padStart(3, '0'))
}

例子:字符串要5位,不够补足01

for (let i = 0; i < 320; i += 10) {
    console.log(i.toString().padStart(5, '01')) // 循环补足01
}

2.3.2 padEnd 从后面补

例子:字符串要3位,不够补足0

for (let i = 0; i < 320; i += 10) {
    console.log(i.toString().padEnd(3, '0'))
}

例子:字符串要5位,不够补足01

for (let i = 0; i < 320; i += 10) {
    console.log(i.toString().padEnd(5, '01')) // 循环补足01
}

2.4 获取对象描述符

Object.getOwnPropertyDescriptor

let o = {
    x: 1,
    y: 2
}

Object.defineProperty(o, 'x', {
    enumerable: false,
    writable: false
})

console.log(Object.getOwnPropertyDescriptors(o))

x: {
    configurable: true
    enumerable: false
    value: 1
    writable: false
}

y: {
    configurable: true
    enumerable: true
    value: 1
    writable: true
}

3.ES9

3.1 for await of ES9异步操作集合如何遍历

用for of 遍历异步操作的时候,不会等异步操作结束后,进行下一次循环,而是一次遍历完,再返回结果

function Gen (time) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(time)
        }, time)
    })
}

function test () {
    let arr = [Gen(1000), Gen(2000), Gen(3000)]
    for (let item of arr) {
        console.log(+new Date(), item.then((time) => {console.log(time)}))
    }
}

test()

改造后

function Gen (time) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(time)
        }, time)
    })
}

async function test () {
    let arr = [Gen(1000), Gen(2000), Gen(3000)]
    for await (let item of arr) {
        console.log(+new Date(), item)
    }
}

test()

3.2 for await of 自定义格式遍历

const obj = {
    count: 1,
    Gen (time) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    value: time,
                    done: false
                })
            }, time)
        })
    },
    [Symbol.asyncIterator] () {
        let _this = this
        return {
            next () {
                _this.count++
                if (_this.count < 4) {
                    return _this.Gen(Math.random() * 1000)
                } else {
                    return Promise.resolve({
                        value: undefined,
                        done: true
                    })
                }
            }
        }
    }
}

async function test () {
    for await (let item of obj) {
        console.log(Date.now(), item)
    }
}
test()

3.3 promise 兜底操作

无论promise执行resolve还是reject,都可以走到finally

function Gen (time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (time < 500) {
                reject(time)
            } else {
                resolve(time)
            }
            
        }, time)
    })
}

Gen(Math.random() * 1000).then((val) => {
    console.log(val)
}).catch((err) => {
    console.log(err)
}).finally(() => {
    console.log('finish')
})

3.4 新增Object的Rest和Spread方法

let input = {
    a: 2,
    b: 3
}

let output = {
    ...input,
    c: 4
}

input.a = 10

console.log(output) // {a: 2, b: 3, c: 4}  浅拷贝 修改input不会影响output
let input = {
    a:1,
    b:3,
    c:4,
    d:4
}

let {a, b, ...rest} = input

console.log(a) // 1
console.log(b) // 3
console.log(rest) // {c: 4, d: 4}

3.5 dotAll、命名分组捕获、后行断言

正则中.不能匹配四个字节的字符,和行终止符

dotAll就可以把.匹配任何字符

console.log(/foo.bar/.test('foo\nbar')) // false

console.log(/foo.bar/s.test('foo\nbar')) // true

之前匹配四个字节的字符,加u修饰符,所以现在加us,点就能匹配所有字符

let reg = /foo.bar/sugi
console.log(reg.dotAll) // true 开启了dotAll模式
consolelog(reg.flags) // gisu 有s就开启了dotAll模式 
let time = '2019-11-12'
const result = time.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)
result.groups.year // 2019
result.groups.month // 11
result.groups.day // 12

先行断言,先遇到一个条件,看后面的满不满足

let test = 'hello world'
test.match(/hello(?=\sworld)/) // 匹配hello 先行断言
test.match(/(?<=hello\=s)world/) // 匹配world 后行断言
test.match(/(?<!hells\=s)world/) // 匹配world 后行断言 不等于

4.ES10

4.1 JSON.stringify

超出一定范围的unicode展示错误的问题得到修复 0xD800 - 0XDFFF

JSON.stringify('\u{D800}') // 以前会报错

4.2 arr.flat()

按照一个可指定的深度,递归扁平化数组,可以传一个参数,代表递归几次,不写默认值是1。

let arr = [1, 2, 3, [3, 4, 5, [5]]]
console.log(arr.flat()) // [1, 2, 3, 3, 4, 5, [5]]
console.log(arr.flat(2)) // [1, 2, 3, 3, 4, 5, 5]
console.log(arr.flat(3)) // [1, 2, 3, 3, 4, 5, 5]

4.3 arr.flatMap()

let arr = [1, 3, 5]
console.log(arr.flatMap(item => [item * 2]))

4.4 str.trim() str.trimStart() str.trimLeft() str.trimEnd() str.trimRight()

let a = '   foo   '
console.log(a.trim())
console.log(a.trimLeft()) // 去除首部空格
console.log(a.trimStart()) // 去除首部空格
console.log(a.trimStart()) // 去除尾部空格
console.log(a.trimStart()) // 去除尾部空格
console.log(a.trim()) // 去除首尾空格

4.5 matchAll

字符串满足条件统统返回

let a = `"foo" and "bar" and "baz"`

function select (reg, str) {
    const matches = []
    for (const match of str.matchAll(reg)) {
        matches.push(match[1])
    }
    return matches
}
console.log(select(/"([^"]*)"/g, a))

4.6 Object.fromEntries(arr)

let arr = [['bar', 1], ['foo', 2]]
let obj = Object.fromEntries(arr)
obj.bar // 1

4.7 try catch

ES5

try {
    
} catch (e) {
    
}

ES10不需要catch后面必须有小括号

try {
    
} catch {
    
}

4.8 BigInt

用来处理2**53的数字

console.log(11n); // 数字后面加个n就是BigInt