1. Object.values()
定义是 Object.values(obj) , obj 参数是对目标对象的操作,它可以是一个对象或者数组。
理解:将对象中的键值顺序存在数组中(若键为数字时,返回的数组以键的值升序排序)
const obj = { x: 'xxx', y: 1 }; 
Object.values(obj); // ['xxx', 1] 
const obj = ['e', 's', '8']; // 等同于 { 0: 'e', 1: 's', 2: '8' }; 
Object.values(obj); // ['e', 's', '8'] 
//当把数字对象的当键的时候,返回的数组以键的值升序排序 
const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' }; 
Object.values(obj); // ['yyy', 'zzz', 'xxx'] 
Object.values('es8'); // ['e', 's', '8']
2. Object.entries
Object.entries 方法返回一个给定对象可枚举属性值的数组[key, value],与 Object.values 类似。
const obj = { x: 'xxx', y: 1 }; 
Object.entries(obj); // [['x', 'xxx'], ['y', 1]] 
const obj = ['e', 's', '8']; 
Object.entries(obj); // [['0', 'e'], ['1', 's'], ['2', '8']] 
const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' }; 
Object.entries(obj); // [['1', 'yyy'], ['3', 'zzz'], ['10', 'xxx']] 
Object.entries('es8'); // [['0', 'e'], ['1', 's'], ['2', '8']]
3.字符串追加
(1) String.padStart(targetLength,[padString])
targetLength:当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回
当前字符串本身。
padString:(可选)填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保
留最左侧的部分,其他部分会被截断,此参数的缺省值为空格。
(2) String.padEnd(targetLength,padString])参数释义同上。
4.异步函数
通俗的理解, async 关键字的作用是告诉编译器对于标定的函数要区别对待。当编译器遇到标定的函数中的 await 关键字时,要暂时停止运行,等到 await 标定的函数处理完毕后,再进行相应操作。如果该函数fulfiled了,则返回值是fulfillment value,否则得到的就是reject value。
下面通过拿普通的promise写法来对比,就很好理解了:
async function asyncFunc() {
    const result = await otherAsyncFunc(); // otherAsyncFunc()返回一个Promise对象 
    console.log(result);
}
// 等同于: 
function asyncFunc() {
    return otherAsyncFunc() // otherAsyncFunc()返回一个Promise对象 
        .then(result => {
            console.log(result);
        });
}
按顺序处理多个异步函数的时候优势更为明显:
async function asyncFunc() {
const result1 = await otherAsyncFunc1();// otherAsyncFunc1()返回一个Promise对
象
console.log(result1);
const result2 = await otherAsyncFunc2();// otherAsyncFunc2()返回一个Promise对
象
console.log(result2);
}
// 等同于:
function asyncFunc() {
return otherAsyncFunc1()// otherAsyncFunc1()返回一个Promise对象
.then(result1 => {
console.log(result1);
return otherAsyncFunc2();// otherAsyncFunc2()返回一个Promise对象
})
.then(result2 => {
console.log(result2);
});
}
并行处理多个异步函数:
async function asyncFunc() {
const [result1, result2] = await Promise.all([
otherAsyncFunc1(),// otherAsyncFunc1()返回一个Promise对象
otherAsyncFunc2() // otherAsyncFunc2()返回一个Promise对象
]);
console.log(result1, result2);
}
// 等同于:
function asyncFunc() {
return Promise.all([
otherAsyncFunc1(),// otherAsyncFunc1()返回一个Promise对象
otherAsyncFunc2() // otherAsyncFunc2()返回一个Promise对象
])
.then([result1, result2] => {
console.log(result1, result2);
});
}
处理错误:
async function asyncFunc() {
try {
await otherAsyncFunc();// otherAsyncFunc()返回一个Promise对象
} catch (err) {
console.error(err);
}
}
// 等同于:
function asyncFunc() {
return otherAsyncFunc()// otherAsyncFunc()返回一个Promise对象
.catch(err => {
console.error(err);
});
}