ES2017(ES8)

118 阅读1分钟

字符串填充(padStart 和 padEnd)

'test'.padStart(10, 'ab') // 'abababtest'
'test'.padEnd(10, 'ab') // 'testababab'

Object.values()

这个方法返回一个包含所有对象自身属性值的数组

const person = {
    name: 'nufeng',
    age: 29
}
Object.values(person) // ['nufeng', 29]

Object.entries()

这个方法返回一个包含所有对象自身属性(key, value)的数组

const person = {
    name: 'nufeng',
    age: 29
}
Object.entries(person) // [['name', 'nufeng'], ['age', 29]]

const p = ['a', 'b']
Object.entries(p) // [[0, 'a'], [1, b]]

Object.getOwnPropertyDescriptors()

此方法返回对象的所有自有(非继承的)属性描述符。

const person = {
    name: 'nufeng',
    age: 29, 
    set youName(newName) {
        console.log(newName)
    }
}
const a = Object.getOwnPropertyDescriptors(person)
// a为
{
    age: {
        configurable: true,
        enumerable: true,
        value: 29,
        writable: true
    },
    name: {
        configurable: true,
        enumerable: true,
        value: "nufeng",
        writable: true
    },
    youName: {
        configurable: true,
        enumerable: true,
        set: youName(newName) {
            console.log(newName)
        }
    }
}
Object.assign()无法复制setter, getter等

Async Functions (异步函数)

Async Functions (异步函数) 是 promises 和 generators(生成器) 的组合,以简化 promises 调用,提过代码的可读性,但是不打破 promises 链式调用的限制。

Async 函数就是 Generator 函数的语法糖。 async相当于*,await相当于yield。

async 表示函数里有异步操作,await 表示紧跟在后面的表达式需要等待结果

function doSomethingAsync() {
    return new Promise((resolve) => {
        setTimeout(() => resolve('I did something'), 3000)
    })
}
async function doSomething() {
    console.log(await doSomethingAsync())
}
console.log('Before')
doSomething()
console.log('After')

// 运行结果
// Before
// After
// I did something //after 3s