zoukankan      html  css  js  c++  java
  • 六个漂亮的 ES6 技巧

    通过参数默认值强制要求传参

    ES6 指定默认参数在它们被实际使用的时候才会被执行,这个特性让我们可以强制要求传参:

    /**

    * Called if a parameter is missing and

    * the default value is evaluated.

    */

    function mandatory() {

        throw new Error("Missing parameter");

    }

    function foo(mustBeProvided = mandatory()) {

        return mustBeProvided;

    }

    函数调用 mandatory() 只有在参数 mustBeProvided 缺失的时候才会被执行。

    在控制台测试:

    > foo()

    Error: Missing parameter

    > foo(123)

    123

    更多内容:

    • 段落: “Required parameters” 。

    通过 for-of 循环来遍历数组元素和索引

    方法 forEach() 允许你遍历一个数组的元素和索引:

    var arr = ["a", "b", "c"];

    arr.forEach(function (elem, index) {

        console.log("index = "+index+", elem = "+elem);

    });

    // Output:

    // index = 0, elem = a

    // index = 1, elem = b

    // index = 2, elem = c

    ES6 的 for-of 循环支持 ES6 迭代(通过 iterables 和 iterators)和解构。如果你通过数组的新方法 enteries() 再结合解构,可以达到上面 forEach 同样的效果:

    const arr = ["a", "b", "c"];

    for (const [index, elem] of arr.entries()) {

        console.log(`index = ${index}, elem = ${elem}`);

    }

    arr.enteries() 通过索引-元素配对返回一个可迭代对象。然后通过解构数组 [index, elem] 直接得到每一对元素和索引。console.log() 的参数是 ES6 中的模板字面量特性,这个特性带给字符串解析模板变量的能力。

    更多内容:

    • 章节: “Destructuring”

    • 章节: “Iterables and iterators”

    • 段落: “Iterating with a destructuring pattern”

    • 章节: “Template literals”

    遍历 Unicode 表示的字符串

    一些 Unicode 编码的字由两个 JavaScript 字符组成,例如,emoji 表情:

    字符串实现了 ES6 迭代,如果你通过迭代来访问字符串,你可以获得编码过的单个字(每个字用 1 或 2 个 JavaScript 字符表示)。例如:

    for (const ch of "xuD83DuDE80y") {

        console.log(ch.length);

    }

    // Output:

    // 1

    // 2

    // 1

    这让你能够很方便地得到一个字符串中实际的字数:

    > [..."xuD83DuDE80y"].length

    3

    展开操作符 (...) 将它的操作对象展开并插入数组。

    更多内容:

    • 章节: “Unicode in ES6”

    • 段落: “The spread operator (...)”

    通过变量解构交换两个变量的值

    如果你将一对变量放入一个数组,然后将数组解构赋值相同的变量(顺序不同),你就可以不依赖中间变量交换两个变量的值:

    [a, b] = [b, a];

    可以想象,JavaScript 引擎在未来将会针对这个模式进行特别优化,去掉构造数组的开销。

    更多内容:

    • 章节: “Destructuring”

    通过模板字面量(template literals)进行简单的模板解析

    ES6 的模板字面量与文字模板相比,更接近于字符串字面量。但是,如果你将它们通过函数返回,你可以使用他们来做简单的模板渲染:

    const tmpl = addrs => `

        

        ${addrs.map(addr => `

            ${addr.first}${addr.last}

        `).join("")}

        

    `;

    tmpl 函数将数组 addrs 用 map(通过箭头函数) join 拼成字符串。tmpl() 可以批量插入数据到表格中:

    const data = [

        { first: "", last: "Bond" },

        { first: "Lars", last: "" },

    ];

    console.log(tmpl(data));

    // Output:

    // //

    //    

    //     Bond

    //

    //     Lars

    //    

    //

    //

    更多内容:

    • 博客文章: “Handling whitespace in ES6 template literals”

    • 段落: “Text templating via untagged template literals”

    • 章节: “Arrow functions”

    通过子类工厂实现简单的合成器

    当 ES6 类继承另一个类,被继承的类可以是通过任意表达式创建的动态类:

    // Function id() simply returns its parameter

    const id = x => x;

    class Foo extends id(Object) {}

    这个特性可以允许你实现一种合成器模式,用一个函数来将一个类 C 映射到一个新的继承了C的类。例如,下面的两个函数 Storage 和 Validation 是合成器:

    const Storage = Sup => class extends Sup {

        save(database) { ··· }

    };

    const Validation = Sup => class extends Sup {

        validate(schema) { ··· }

    };

    你可以使用它们去组合生成一个如下的 Employee 类:

    class Person { ··· }

    class Employee extends Storage(Validation(Person)) { ··· }

    更多信息:

    • 段落: “Simple mixins”

    下面的两个章节提供了很好地概括了 ECMAScript 6 的特性:

    • An overview of what’s new in ES6

    • First steps with ECMAScript 6 [features that are easy to adopt]

  • 相关阅读:
    HDU 4278 Faulty Odometer 8进制转10进制
    hdu 4740 The Donkey of Gui Zhou bfs
    hdu 4739 Zhuge Liang's Mines 随机化
    hdu 4738 Caocao's Bridges tarjan
    Codeforces Gym 100187M M. Heaviside Function two pointer
    codeforces Gym 100187L L. Ministry of Truth 水题
    Codeforces Gym 100187K K. Perpetuum Mobile 构造
    codeforces Gym 100187J J. Deck Shuffling dfs
    codeforces Gym 100187H H. Mysterious Photos 水题
    windows服务名称不是单个单词的如何启动?
  • 原文地址:https://www.cnblogs.com/jiechen/p/5572280.html
Copyright © 2011-2022 走看看