ES 6の新しい特性と重点知識の総括

9121 ワード

一、ES 6変数宣言
  • varが宣言した変数で、「ブロックレベルの役割ドメイン」の制限はありません.
  • let/const宣言の変数で、「ブロックレベルの役割ドメイン」があります.
  • {
        var a = 1;
        let b = 2;
        const c = 3;
        let fn = function() {
            console.log(4)
        }
    }
    
    console.log(a);   // 1
    console.log(b);   //   ReferenceError,undefined
    console.log(c);   //   ReferenceError,undefined
    fn();       // ReferenceError: fn is not defined
    
  • varが宣言した変数には「変数昇格」が存在し、let/constは存在しません.
  • var tmp = new Date();
    
    function fn() {
        console.log(tmp);
        if (false) {
            // var tmp     
            var tmp = 'hello world';
        }
    }
    fn()
    
  • constは定数を宣言し、変更できません.
  • const c = 1;
    c = 2;      // TypeError  
    

    二、解構賦値
    ES 6は、一定のパターンに従って配列およびオブジェクトから値を抽出し、変数に値を付与することを可能にし、これを解構と呼ぶ.
  • 配列解構賦値
  • let arr = [1, 'hello', [100,200], {a:1, b:2}, true, undefined];
    
    let [a, b, c, d, e, f] = arr
    
    console.log(a,b,c,d,e,f)
    
  • は、解構賦値を用いて、2つの変数の値
  • を交換する.
    let x = 1, y = 2;
    [x, y] = [y, x]
    console.log(x, y)
    
  • オブジェクト解構賦値
  • let obj = {
        a: 1,
        b: [1,2,3],
        c: false,
        d: {name: 'geekxia', age: 10 }
    }
    
    let { a, b, c, d, e } = obj
    console.log(a, b, c, d, e)
    
    //   
    let { b: bb } = obj
    console.log(bb)
    

    三、文字列方法の拡張
    let str = 'hello world, my name is geekxia.';
    
    //           
    console.log(str.charAt(0))
    
    //               ,         ,       -1
    console.log(str.indexOf('name0'))
    
    //              ,     
    console.log(str.includes('geekxia'))
    
    //               ,     
    console.log(str.startsWith('he'))
    //               ,     
    console.log(str.endsWith('he'))
    
    //       n ,       
    console.log(str.repeat(2))
    
    //           ,       
    console.log(str.padStart(100, '01'))
    //           ,       
    console.log(str.padEnd(100, '01'))
    

    四、Math方法の拡張
    ES 6はMathオブジェクトに数学に関する17の方法を追加した.
    //        
    console.log(Math.trunc(5.5))
    
    //         (1),  (-1),   (0)
    console.log(Math.sign(0))
    
    //      
    console.log(Math.cbrt(-8))
    
    //              
    console.log(Math.hypot(3, 4))
    
    //      
    console.log(2**4)
    

    五、関数拡張
  • 関数と解構賦値を組み合わせて
  • を使用する
    function add ({ a = 0, b = 0 }) {
        console.log(a + b)
    }
    add({a:2, b:3})  // 5
    add({a:2})  // 2
    add({})     // 0
    add()   //   
    
  • 関数のrestパラメータ
  • function sum(...values) {
        let total = 0;
        for (let value of values) {
            total += value
        }
        console.log(total)
    }
    sum(1,2,3)
    //      
    sum(1,2,3,4,5,)
    

    六、矢印関数
    let f1 = v => v;
    let f2 = () => 5;
    let f3 = (a, b) => a + b;
    
    console.log(f1(1))
    console.log(f2())
    console.log(f3(1,2))
    
  • カッコはコードブロックとして解釈されるため、矢印関数が直接オブジェクトに戻る場合は、オブジェクトの外にカッコを付ける必要があります.
  • //       ,    ()  
    let f4 = (a, b) => ({a, b})
    console.log(f4(1,2))
    

    七、拡張演算子
    拡張演算子(spread)は3つの点(...)です.restパラメータの逆演算のように、配列をカンマで区切ったパラメータシーケンスに変換します.
  • 配列の動作、連結
  • let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];
    
    let arr = [...arr1, ...arr2, 7, 8, 9, 10];
    console.log(arr)
    
  • は解構賦値と協力し、配列の切り取り
  • を実現する.
    let arr = [1, 2, 3, 4, 5, 6]
    
    let [a, b, ...arr1] = arr
    console.log(arr1)
    
  • オブジェクトの操作、マージ:
  • let obj1 = { a:1, b:2 }
    let obj2 = { c:3, d:4 }
    
    let obj = { ...obj1, ...obj2, e:5, a:6 }
    console.log(obj)
    
  • は、解体賦値と協働し、操作対象:
  • let obj = { a:1, b:2, c:3, d:4, e:5 }
    let { a, b, ...obj1 } = obj
    console.log(obj1)
    

    八、Array拡張
  • クラス配列を真の配列に変換する:
  • let arrayLike = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        length: 3
    }
    
    var arr = Array.from(arrayLike);   
    console.log(arr)  // ['a', 'b', 'c']
    
  • は、値のセットを配列に変換します.Array.ofは常にパラメータ値からなる配列を返します.パラメータがない場合は、空の配列を返します.
  • let a = Array.of(1,2);  // [1, 2]
    let b = Array.of();     // []
    let c = Array.of(undefined);  // [undefined]
    
    console.log(a)
    console.log(b)
    console.log(c)
    
  • 配列インスタンスのfindメソッドは、条件を満たす最初の配列メンバーを見つけるために使用されます.そのパラメータはコールバック関数であり、すべての配列メンバーがコールバック関数を順次実行し、最初の戻り値がtrueのメンバーが見つかり、メンバーが返されます.条件を満たすメンバーがいない場合はundefinedを返します.
  • let res1 = [1,2,-5,10].find((ele,index,arr) => ele < 0);
    console.log(res1)
    
  • 配列インスタンスのfindIndexメソッドの使用方法はfindメソッドと非常に類似しており、最初の条件を満たす配列メンバーの位置を返し、すべてのメンバーが条件を満たさない場合は-1を返します.
  • let res2 = [1,5,10,15].findIndex((ele,index,arr) => ele > 9);
    console.log(res2)
    
  • 配列充填
  • let res3 = new Array(4).fill(7);
    console.log(res3)
    
  • 指定配列に値が含まれているか否かを判断する
  • .
    let arr = [1, 2, 3]
    console.log([1,2,3].includes(2))
    console.log([1,2,3].includes(0,1))  //          
    

    九、json拡張
    ES 6は、オブジェクトの属性およびメソッドとして変数および関数を直接書き込むことを可能にする.このような書くのはもっと簡潔だ.
    let foo = 'geekxia'
    function fn1() {
        console.log(1)
    }
    const obj = {
        foo,
        bar: 'hello',
        fn1,
        fn2() {
            console.log(2)
        },
        fn3: function() {
            console.log(3)
        }
    }
    
    obj.fn1()
    obj.fn2()
    obj.fn3()
    

    十、Symbolタイプ
    ES 6は、ユニークな値を表す新しい元のデータ型Symbolを導入した.JavaScript言語の7番目のデータ型で、最初の6つはundefined、null、Boolean値(Boolean)、文字列(String)、数値(Number)、オブジェクト(Object)です.
    十一、Set構造
    ES 6は新しいデータ構造Setを提供する.配列に似ていますが、メンバーの値は一意で、重複する値はありません.Set自体は、Setデータ構造を生成するための構造関数です.
  • Set構造を使用して、配列の重量除去
  • を実現する.
    let arr1 = [1,2,2,2,3,4]
    let arr2 = [...new Set(arr1)]
    console.log(arr2)
    

    十二、Map構造
    ES 6は、Mapデータ構造を提供する.オブジェクトに似ており、キー値ペアの集合でもありますが、「キー」の範囲は文字列に限定されません.オブジェクトを含む様々なタイプの値はキーとして使用できます.つまり、Object構造は「文字列-値」の対応を提供し、Map構造は「値-値」の対応を提供し、より完璧なHash構造の実現です.「キー値ペア」のデータ構造が必要な場合は、MapはObjectより適切です.
    const map = new Map();
    
    map.set({ p: 'hello world'}, 1)
    map.set('hello', [1,2,3])
    
    console.log(map.size)
    

    十三、Promise
    Promiseは非同期プログラミングのソリューションであり、従来のソリューションであるコールバック関数とイベントよりも合理的で強力です.
    let promise = new Promise(function(resolve, reject) {
        setTimeout(()=>{
            if(false) {
                resolve('ok')
            } else {
                reject({err: -1, msg: '     '})
            }
        }, 1000)
    })
    
    promise.then(res=>{
        console.log(res)
    }).catch(err=>{
        console.log(err)
    }).finally(()=>{
        console.log('    ')
    })
    

    十四、循環遍歴
  • ES 6はC++、Java、C#、Python言語を参考にforを導入しました...ofループは,すべてのデータ構造を遍歴する統一的な方法として用いられる.
  • for...ofループで使用できる範囲は、配列、SetおよびMap構造、argumentsオブジェクト、DOM NodeListオブジェクトなどのいくつかの類似配列のオブジェクト、Generatorオブジェクト、および文字列です.
  • for...ofはbreak/continue/returnと組み合わせて使用できます.
  • let arr = [1, 2, 3, 4, 5]
    for(let ele of arr) {
        if (ele > 2) {
            break
        }
        console.log(ele)
    }
    
  • 普通のオブジェクトに対してfor...of構造は直接使用できず、エラーが報告されます.forを使用...inは、通常のオブジェクトを巡回します.
  • let obj = {
        a: 1,
        b: 2,
        c: 3
    }
    for(let k in obj) {
        console.log(obj[k])
    }
    

    十五、async/await
    function add(a,b) {
    //     promise  
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve(a+b)
            }, 2000)
        })
    }
    
    // await is only valid in async function
    // await    async     
    async function testAdd() {
        let num = await add(2,3)
        console.log(num)
    }
    
    testAdd()
    

    十六、classクラスと継承
    class Point {};
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);   //       constructor(x, y)
            this.color = color;
        }
        toString() {
            return this.color + ' ' + super.toString();  //      toString()  
        }
    }
    

    十七、ES 6モジュール化
  • export defaultを使用する放出モジュール
  • .
    export default xxx;   //     
    
    import xxx from './xxx'   //     
    
  • exportを使用する放出モジュール
  • .
    export const a = 1;
    export function foo() {}   //   
    
    import { a, foo } from './xxx'   //   
    

    十八、装飾器
    多くのオブジェクト向け言語には、クラスの動作を変更するための修飾器(Decorator)関数があります.
  • アクセサリークラスを修飾するために使用されます:
  • @decorator
    class A {};
    
  • アクセサリークラスを修飾する方法:
  • class Person {
        @readonly
        name() { return `${this.name}` }
    }
    

    リソースノートの推奨事項:
  • let変数とconst定数
  • ES 6関数宣言
  • global最上位オブジェクト
  • 解構賦値
  • Unicode符号化
  • String拡張とテンプレート文字列
  • RegExp拡張
  • Number拡張
  • Math拡張
  • Function拡張
  • ES 6矢印関数
  • ES 6拡張演算子
  • Array拡張
  • JSON拡張
  • Object拡張
  • Symbolタイプ
  • Set構造
  • Map構造
  • Proxyエージェントブロック
  • Reflectオブジェクト
  • Promiseオブジェクト
  • Iterator遍歴器
  • for...ofループ
  • Generator関数
  • async非同期関数
  • classクラスと継承
  • ES 6デコレーション
  • ES 6モジュール化
  • ES 6エンコーディングスタイル
  • ES 6バイナリ配列動作
  • 本編終了2019年11月08日