Skip to content

ECMAScript 2017 (8)

特性一览

字符串填充

  • padStart()

从左侧开始用另一个字符串填充当前字符串至指定长度

js
const str = "123456789";
const last4str = str.slice(-4);
last4str.padStart(str.length); // '     6789' //[!code focus]
last4str.padStart(str.length, "*"); // '*****6789' //[!code focus]
  • padEnd()

从右侧开始用另一个字符串填充当前字符串至指定长度

js
const str = "123456789";
str.padEnd(10); //'123456789 ' //[!code focus]
str.padEnd(10, "*"); //'123456789*' //[!code focus]

async/await

async 函数是 AsyncFunction 构造函数的实例,并且其中允许使用 await 关键字。

async 和 await 关键字让我们可以用一种更简洁的方式写出基于 Promise 的异步行为,而无需刻意地链式调用 promise。

js
const wait2s = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("resolved");
    }, 2000);
  });
};

const asyncCall = async () => {
  console.log("calling");
  const result = await wait2s();
  console.log(result); // resolved
};

asyncCall();

对象新增的方法

  • getOwnPropertyDescriptors()

用来获取一个对象的所有自身属性的描述符。

js
const obj = { age: 22 };
Object.getOwnPropertyDescriptors(obj, "age"); //[!code focus]
  • entries()

返回一个数组,包含给定对象自有的可枚举字符串键属性的键值对。

js
const obj = {
  name: "baizhi958216",
  age: 22,
};
// "name: baizhi958216"
// "age: 22"
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}
  • values()

返回一个给定对象的自有可枚举字符串键属性值组成的数组。

js
const obj = {
  name: "baizhi958216",
  age: 22,
};
Object.values(obj); // Array ["baizhi958216", 22] //[!code focus]