🌮微卷不亏,4 分钟再快速过一遍 ES12 的 5 个要点~

·  阅读 1342
🌮微卷不亏,4 分钟再快速过一遍 ES12 的 5 个要点~

这是我参与11月更文挑战的第13天,活动详情查看:2021最后一次更文挑战


本篇译自:levelup.gitconnected.com/top-5-javas…

什么叫“微卷不亏”?意思就是学习知识点,稍微卷一卷,也不会很累,也不会被其他人卷死,就稍微卷一卷,永远不亏,甚至小赚一波,唉,很舒服~~

ES12 是今年 6 月 22 日发布的,你已经用起来了吗?

留下 4 分钟,本篇带你快速过一遍 ES12 的 5 个要点!!

1. 数字分隔符

数字分隔符是数字之间添加的下划线,这使得数字更可读;当代码解析时,下划线会被自动去除;

举栗🌰

// 十进制数字,按照千位进行划分
let n1 = 1_000_000_000;
console.log(n1); // This will print: 1000000000

// 十进制数字,按照千位进行划分,带小数点
let n2 = 1_000_000_000.150_200
console.log(n2); // This will print: 1000000000.1502

// 十六进制数字,按照字节分组
let n3 = 0x95_65_98_FA_A9
console.log(n3); // This will print: 641654651561

// 大文字,按千位划分
let n4 = 155_326_458_156_248_168_514n
console.log(n4); // This will print: 155326458156248168514n
复制代码

2. replaceAll

我们之前是 "abca".repalce(/a/g,"a1") 这样写正则的方式实现替换全部,现在直接用 replaceAll() 就可以了~

举栗🌰

// 声明一个字符串
const orgStr = 'JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled and multi-paradigm.';

// 用 replace 替换第一个选中元素
let newStr = orgStr.replace('JavaScript', 'TypeScript');
console.log(newStr);

// 用 replaceAll 替换所有选中元素
let newStr2 = orgStr.replaceAll('JavaScript', 'TypeScript');
console.log(newStr2);
复制代码

3. Promise.any()

Promise.any()Promise.all() 相对:

前者是执行的 Promise 数组中,只要有其中一个 Promise resolve(或全部 reject) 则会进入 .then(或 .catch);

而后者是全部 Promise resolve(或有一个 reject),才会进入 .then(或 .catch)。

举栗🌰:任一 Promise resolve 即返回

// 创建 promise1
const promise1 = new Promise((resolve, reject) => {
    // 2 秒后 resolve
    setTimeout(() => resolve("The first promise has been resolved."), 2000);
});

// 创建 promise2
const promise2 = new Promise((resolve, reject) => {
    // 1 秒后 resolve
    setTimeout(() => resolve("The second promise has been resolved."), 1000);
});

// 创建 promise3
const promise3 = new Promise((resolve, reject) => {
    // 3 秒后 resolve
    setTimeout(() => resolve("The third promise has been resolved."), 3000);
});

(async function () {
    const data = await Promise.any([promise1, promise2, promise3]);
    // 第一个 resolve 后,立即返回给 data
    console.log(data);
    // 打印信息: The second promise has been resolved.
})();
复制代码

举栗🌰:全部 Promise reject 即返回

// 创建 promise1
const promise1 = new Promise((resolve, reject) => {
    // After 1 second reject the first promise.
    setTimeout(() => reject("The first promise has been rejected."), 1000);
});

// 创建 promise2
const promise2 = new Promise((resolve, reject) => {
    // After 500 miliseconds reject the second promise.
    setTimeout(() => reject("The second promise has been rejected."), 500);
});

// 立即执行
(async function () {
    try {
        const data = await Promise.any([promise1, promise2]);
        console.log(data);
    } catch (error) {
        // 全部 Promise reject 则返回;
        console.log("Error: ", error);
        // 打印信息:Error:  AggregateError: All promises were rejected
    }
})();
复制代码

4. 三个逻辑赋值

ES12 引入了 3 个新的逻辑赋值运算符:

  • ||= 逻辑或赋值,等同于:a || (a = b)
  • &&= 逻辑与赋值,等同于:a && (a = b)
  • ??= 逻辑合并赋值,等同于:a ?? (a = b)

举栗🌰:||=

// 当 ||= 左侧的值是 false,则更改赋值为等号后的值
let myPlaylist = {songsCount: 0, songs:[]};
myPlaylist.songsCount ||= 100;
console.log(myPlaylist); // This will print: {songsCount: 100, songs: Array(0)}
复制代码

举栗🌰:&&=

// 当 &&= 左侧的值是 true,则更改赋值为等号后的值
let myFiles = {filesCount: 100, files:[]};
myFiles.filesCount &&= 5;
console.log(myFiles); // This will print: {filesCount: 5, files: Array(0)}
复制代码

举栗🌰:??=

// 当 ??= 左侧的值是 null or undefined,则更改赋值为等号后的值
let userDetails = {firstname: 'Katina', age: 24}
userDetails.lastname ??= 'Dawson';
console.log(userDetails); // This will print: {firstname: 'Katina', age: 24, lastname: 'Dawson'}
复制代码

5. 私有类方法/属性

Class 默认情况下类方法和属性都是公共的,在 ES12 中可以用 # 加一个前缀符号创建私有的方法和属性;

// 创建 User 类
class User {
    constructor() {}

    // 加 # 井号设为私有方法
    #generateAPIKey() {
        return "d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767";
    }

    getAPIKey() {
        // 调用私有方法
        return this.#generateAPIKey();
    }
}

const user = new User();
const userAPIKey = user.getAPIKey();
console.log(userAPIKey); // This will print: d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767
复制代码

同时,类里面也可以设置私有的 GetterSetter

// 创建 Str 类
class Str {
    // 设置私有属性
    #uniqueStr;

    constructor() {}

    // 私有 Setter
    set #generateUniqueStringByCustomLength(length = 24) {
        const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let randomStr = "";

        for (let i = 0; i < length; i++) {
            const randomNum = Math.floor(Math.random() * characters.length);
            randomStr += characters[randomNum];
        }

        this.#uniqueStr = randomStr;
    }

    // 公共 Setter
    set setRandomString(length) {
        this.#generateUniqueStringByCustomLength = length;
    }

    // 私有 Getter
    get #fetchUniqueString() {
        return this.#uniqueStr;
    }

    // 公共 Getter
    get getRandomString() {
        return this.#fetchUniqueString;
    }
}

const str = new Str();
// 调用公共 Setter,然后访问私有 Setter
str.setRandomString = 20;

// 调用公共 Getter,然后访问私有 Getter
const uniqueStr = str.getRandomString;
console.log(uniqueStr); // 每次在 Setter 之后执行 Getter ,将打印一个随机字符串
复制代码

OK,以上便是本篇分享,周末愉快O(∩_∩)O,我是掘金安东尼,公众号同名,日拱一卒、日掘一金,再会~~