かいせつごう

2321 ワード

基本概念


さぎょう


解体は、組織化されたオブジェクトまたは配列から情報クリップを抽出する

条件

  • は、情報セグメントがどのオブジェクトまたは配列
  • から抽出するかを明確にする.
  • は、オブジェクトのどの属性または配列のいくつかの要素
  • を抽出するかを明確にする.

    その他


    情報セグメントの抽出に加えて、いくつかの補助的な機能があります.
  • は、抽出できない可能性のある情報のデフォルト値
  • を設定する.
  • 抽出された情報の名前を変更する
  • シーン


    解構の使用シーンは,変数付与を宣言する段階だけでなく,単純にある変数に再付与することもできる.
    関数パラメータでの解体の使用

    例を挙げる

    let node = {
        type: 'Identify',
        name: 'foo',
        subNode: {
            name: 'subFoo'
        }
    }
    
    let {
        type, //   node type  
        name: myname, //   node name  ,     myname
        text, //   node text  ,           ,  undefined
        value: myvalue = 'gaga', //   node value  ,     myvalue,    ,  'gaga'
        subNode: { //   node subNode  name  ,     subName,    
            name: subName
        }
    } = node //  node       
    
    type // 'Identify'
    text // undefined
    value // ReferenceError
    myvalue // 'gaga'
    subName // 'subFoo'

    上のコードは下のコード出力と同じです
    let node = {
        type: 'Identify',
        name: 'foo',
        subNode: {
            name: 'subFoo'
        }
    }
    
    let type,
        myname,
        text,
        myvalue = 'hehe',
        subName
    
    ({
        type,
        name: myname,
        text,
        value: myvalue = 'gaga',
        subNode: {
            name: subName
        }
    } = node)

    はいれつかいそう


    オブジェクトの解体との相違点

  • オブジェクトは、属性名によって情報セグメントを示す、配列は、位置によって情報
  • を示す.
  • オブジェクトの解体デフォルトでは、抽出された情報は属性名と同じ変数に割り当てられ、配列は抽出された情報に
  • と命名する必要がある.
  • は、変数
  • を交換するために使用することができる.

    例を挙げる

    let colors = ["red", "green", "blue"]
    let [,,thirdColor] = colors //  colors        2   
    let [firstColor] = colors //  colors        0   
    let [,secondColor,,fourthColor] = colors 
    //  colors        1 3   ,        undefined
    let [,secondColor,,fourthColor = "yellow"] = colors //      
    //     
    let colors = ["red", ["green", "lightgreen"], "blue"]
    let [, [,subColor],] = colors
    //     
    let colors = ["red", "green", "lightgreen", "blue"]
    let [first, ...others] = colors
    others // ["green", "lightgreen", "blue"]
    //     
    let a = 1,
        b = 2;
    [a, b] = [b, a]