async/await
async/await 是 Promise + generator 的语法糖,详见
/* async 函数返回一个 Promise */
async function firstAsync() {
return 27
}
// 相当于
// function firstAsync() {
// return Promise.resolve(27)
// }
console.log(firstAsync()) // Promise {<resolved>: 27}
console.log(firstAsync() instanceof Promise) // true
// -------------------------------------------
// await 必须写在 async 函数中
// await 之后会变成 Promise
async function secondAsync() {
const a = await 11
}
// 相当于
// async function secondAsync() {
// const a = await Promise.resolve(11)
// }
// await 关键字会等待之后的 Promise 完成了才继续执行
// 这里 await 暂停执行就是 generator 的特性
Object
遍历
Object.keys(obj): Array
// 相当于
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const element = obj[key]
}
}
Object.values(obj): Array
Object.entries(obj): Array
const obj = { x: 1, y: 2 }
// TypeError: obj is not iterable
// for (const iterator of obj) {
// console.log(iterator)
// }
// 正确做法
for (const [k, v] of Object.entries(obj)) {
console.log(iterator)
}
// x 1
// y 2
获取 Object 的属性描述符
const data = {
PortLand: '78/50',
Dublin: '88/52',
Lima: '58/40'
}
Object.defineProperty(data, 'Lima', {
enumerable: false // 不可遍历
})
console.log(Object.keys(data)) // ['PortLand', 'Dublin']
console.log(Object.getOwnPropertyDescriptors(data))
// {
// Dublin: {value: "88/52", writable: true, enumerable: true, configurable: true},
// Lima: {value: "58/40", writable: true, enumerable: true, configurable: true},
// PortLand: {value: "78/50", writable: true, enumerable: true, configurable: true}
// }
Object.getOwnPropertyDescriptor(data, 'Lima')
// {value: "58/40", writable: true, enumerable: true, configurable: true}
String
对 String 补白
String.prototype.padStart(需要的长度, 用什么补)
String.prototype.padEnd(需要的长度, 用什么补)