破壊を理解する


導入


破壊は、JavaScriptのES 6バージョンで導入された非常に強力な機能です.この記事は、あなたが破壊について知っている必要があるすべてについての包括的な概要を提供します.
  • なぜ破壊されるのか?
  • 何が破壊されているか.
  • 物を破壊しているオブジェクト
    を破壊しているアレイ
  • 混合爆破
  • の機能破壊

    破壊する理由


    JavaScriptでコーディングしている場合は、ネストしたオブジェクトにアクセスする必要があるシナリオに遭遇したでしょう.特に、あなたのアプリケーションをサードパーティのAPIと統合する場合、これは本当です.APIから受け取られたJSON応答で働く必要がしばしばあります、そして、オブジェクト構造は入れ子になった要素としばしば複雑です.
    複雑な入れ子になった要素にアクセスすることは、我々が破壊を使用するのが正確に'理由'です.これは、複雑な構造の抽出を簡素化する方法を提供します.
    次のコード例を見てみましょう.
    //Employee Variable containing nested address for Home and Work
    const employee = {
      name: 'Skay',
      age: 32,
      address: {
          line1: '1480 Rachel Garden',
          city: 'Pine Brook',
          state: 'NJ',
          country: 'USA',
      }
    };
    
    //Function displays the Home Address individually
    function displayHomeAddress(employee) {
        console.log(`The name of the employee is ${employee.name}`);
      console.log(`The Home Address line 1 is ${employee.address.line1}`);
      console.log(`The Home City is ${employee.address.city}`);
      console.log(`The Home State is ${employee.address.state}`);
      console.log(`The Home Country 1 is ${employee.address.country}`);
    }
    
    //Call the displayHomeAddress() function
    displayHomeAddress(employee);
    
    /*
    The name of the employee is Skay
    The Home Address line 1 is 1480 Rachel Garden
    The Home City is Pine Brook
    The Home State is NJ
    The Home Country 1 is USA
    */
    
    上記のコード例から2つの主なものがあります.
  • ネストされたオブジェクト内の値にアクセスする方法は、アクセスの各点で入力されるコードをより多く引き出します.
  • Typoを持つ確率は、オブジェクト内の入れ子になった要素にアクセスするためにより長い文をタイプしようとしている間、より多くです.
  • これは、通常、大きなコードベースを持つ実生活プロジェクトでは、単一のファイルの問題の多くのように見えないかもしれませんが、多くのネストされたオブジェクトに対処し、同じように破壊すると、はるかにシンプルでコンパクトな構文で達成することができます.

    破壊は何か


    JavaScriptでは、オブジェクトと配列を使用している間、複雑な構造を扱う必要があります.破壊することは、そのような複雑な構造をより単純な部分に分解するプロセスです.
    破壊を使用すると、上記のコードスニペットは次のようになります.
    const employee = {
      name: 'Skay',
      age: 32,
      address: {
          line1: '1480 Rachel Garden',
          city: 'Pine Brook',
          state: 'NJ',
          country: 'USA',    
      }
    };
    
    // Object Destructuring - The left hand side represents the elements that need to be extracted from the parent element
    // The right hand side references the parent complex element from which values need to be extracted
    const { name } = employee;
    const { line1, city, state, country } = employee.address;
    
    function displayHomeAddress(employee) {
      console.log(`The name of the employee is ${name}`);
      console.log(`The Home Address line 1 is ${line1}`);
      console.log(`The Home City is ${city}`);
      console.log(`The Home State is ${state}`);
      console.log(`The Home Country 1 is ${country}`);
    }
    
    displayHomeAddress(employee);
    
    /*
    The name of the employee is Skay
    The Home Address line 1 is 1480 Rachel Garden
    The Home City is Pine Brook
    The Home State is NJ
    The Home Country 1 is USA
    */
    
    注意するカップル
  • カール要素括弧{ }の間に抽出する要素を配置する必要があります.
  • 破壊された構文は{ elementToBeExtract } = ' parentElement 'として表現できます.ElementToBeExtractは親要素の直接子でなければなりません.
  • 上記の例では、「名前」は「従業員」要素の直接の子です.同様に、変数' line1 '、' city '、' state '、' country 'はドット演算子を使ってアクセスされる要素' address 'の直接の子です.(従業員住所)

    オブジェクトの破壊


    上記のコードスニペットは、オブジェクトの破壊の例です.別の例を見てみましょう.そうすれば、私たちは本当にその概念を強化することができます.
    //Person object - Simple (No nesting)
    const person = {
      name: 'Skay',
      age: 38,
      skills: 'JavaScript',
    };
    
    // Object Destructuring
    const { name, age, skills } = person;
    
    //Display the output to the console
    console.log(name, age, skills);
    
    //Output -> Skay 38 JavaScript
    
    上で見たように、左側は代入式で、親要素から直接子要素を抽出します.
    別のコード例を取りましょう.
    //Employee Object containing the name, age and skills as atrributes
    const employee = {
      name: 'John',
      age: 25,
      skills: 'HTML CSS',
    };
    
    // Object Destructuring - It is assigned to a 'let' and not a 'const' for reassignment
    let { name, age, skills } = employee;
    
    //Display the output to the console
    console.log(name, age, skills);
    
    //Output -> John 25 HTML CSS
    
    //Employee Object also containing the name, age and skills as atrributes
    const person = {
      name: 'Skay',
      age: 38,
      skills: 'JavaScript',
    };
    
    // Object Destructuring - Reassigning the 'name' 'age' and 'skills' to the new values extracted from person object
    ({ name, age, skills } = person);
    
    //Display the output to the console
    console.log(name, age, skills);
    
    //Output -> Skay 38 JavaScript
    
    注意事項
    最初に、値「名前」、「年齢」と「技術」は『従業員』オブジェクトから破壊されました.
  • desturctured値は、変数(let)の名前、年齢とスキルに割り当てられた.
  • すぐに、再び破壊を使用して、我々は「人」オブジェクトから値名、年齢と技術を抽出して、「名前」、「年齢」、「技術」変数に再割り当てしました.
  • 「名前」、「age」、「スキル」の代入式に括弧(())を囲う使用が必要でした.省略されるならば、破壊しているオブジェクトリテラルはブロック声明と考えられて、エラーを投げます.
  • 要約する
  • 、我々は破壊を通してローカル変数名、年齢と技術に新しい値を再割り当てしました.
  • デフォルト値


    破壊中に変数にデフォルト値を割り当てることができます.そうすることができないので、値'未定義'は破壊された変数に割り当てられます.
    const person = {
      name: 'Skay',
      age: 38
    };
    
    // Assign default value of Canada to country if undefined
    const { name, age, country = 'Canada' } = person;
    
    // Here I am using ES6 template literals
    console.log(`I am ${name} from ${country} and I am ${age} years old.`);
    
    // Output -> I am Skay from Canada and I am 38 years old.'
    
    上記の例では、「国」は「人」オブジェクトで定義されませんでした、そして、それは破壊の間、「カナダ」のデフォルト値を割り当てられました.
    しかし、実際の値が'国'オブジェクトに渡された場合、以下のコードスニペットに示すようにデフォルト値は表示されません.
    const person = {
      name: 'Skay',
      age: 38,
        country: 'India'
    };
    
    // Assign default value of Canada to country if undefined
    const { name, age, country = 'Canada' } = person;
    
    // Here I am using ES6 template literals
    console.log(`I am ${name} from ${country} and I am ${age} years old.`);
    
    // Output -> I am Skay from India and I am 38 years old.'
    

    異なる変数名の使用による破壊


    これまで見た例では、変数名を対応するオブジェクトキーと一致させました.しかし、以下のsytaxを使用して破壊する際に、変数に別の名前を使用することができます.
    異なる変数名を使用する構文→ [オブジェクト名キー]
    以下のコード例を見てみましょう.
    const person = {
      name: 'Skay',
      age: 38,
        country: 'India'
    };
    
    // Assign default value of Canada to country if undefined
    const { name: fullName, age: years, country: place = 'Canada' } = person;
    
    // Here I am using ES6 template literals
    console.log(`I am ${fullName} from ${years} and I am ${place} years old.`);
    
    // Output -> I am Skay from India and I am 38 years old.'
    
    注意事項
  • 変数名「年齢」と「国」を対象者から抽出し、それぞれ「フルネーム」、「年」、「国」に割り当てられた.
  • デフォルト値代入は、異なる変数に割り当てることと共に使用されます.
  • ネストしたオブジェクトの破壊


    この記事の最初の例を見れば、ネストした要素を含むアドレスフィールドを持つ従業員オブジェクトを持っていました.
    この例では、次のように2つの個別行のコードを破壊する方法を示しました
    const { name } = employee;
    const { line1, city, state, country } = employee.address;
    
    以下に示すように、1つの線で破壊することができます.これはネストした破壊と呼ばれます.
    const {  name, address: { line1, city, state, country } } = employee;
    
    ネストした破壊シナリオに対して実行できる完全なコードスニペットです.
    //Employee Object containing nested elements
    const employee = {
      name: 'Skay',
      age: 32,
      address: {
        line1: '1480 Rachel Garden',
        city: 'Pine Brook',
        state: 'NJ',
        country: 'USA'
      },
    };
    
    // Nested Object Destructuring - Use the child element 'address' as a reference 
    // to further destructure to get nested inner elements line1, city, state & country
    const {  name, address: { line1, city, state, country } } = employee;
    
    function displayHomeAddress(employee) {
      console.log(`The name of the employee is ${name}`);
      console.log(`The Home Address line 1 is ${line1}`);
      console.log(`The Home City is ${city}`);
      console.log(`The Home State is ${state}`);
      console.log(`The Home Country 1 is ${country}`);
    }
    
    displayHomeAddress(employee);
    
    私はこれで、オブジェクトの破壊に関連していることをすべてカバーしました.アレイ破壊に飛び込もう.

    アレイ破壊


    配列の破壊はオブジェクトの破壊に非常に似ています.以下の例を見てみましょう.
    // A const representing rgb
    const animal = ['cat', 'dog', 'rat'];
    
    // Array Destructuring
    const [cat, dog, rat] = animal;
    
    //Display the value of R, G, B on the console
    console.log(`${cat}, ${dog}, ${rat}`); 
    
    // Output -> cat, dog, rat
    
    注意事項
  • 変数CAT、Dog、Ratは、動物配列の配列破壊を通して、「猫」、「犬」と「ネズミ」の値を割り当てられました.
  • 各変数は' Animal '配列の同じインデックスで対応する項目にマップされます.
  • デフォルト値


    我々がオブジェクト破壊にデフォルト値代入をする方法のように、我々は同様に配列破壊のためにすることができます.
    // A const representing rgb
    const animal = ['cat', 'dog'];
    
    // Array Destructuring - Default value assignment
    const [cat, dog, rat = 'rat'] = animal;
    
    //Display the value of R, G, B on the console
    console.log(`${cat}, ${dog}, ${rat}`);
    
    // Output -> cat, dog, rat
    
    上記の例では、変数ラットは、破壊の段階で「ネズミ」のデフォルト値を設定されています.

    選択した要素を配列から削除する


    破壊する力を使用して、配列から要素の指定されたセットを選択できます.別のコード例を見てみましょう.
    //Numbers array
    const numbers = [100, 200, 300, 400, 500];
    
    //Skip the elements that you do not want to extract
    const [, , three, four] = numbers;
    
    //Display on the console
    console.log(three, four);
    
    //Output -> 300 400
    
    上の例では、親配列から抽出したくない要素をスキップできます.コンマ区切り文字を使用して、配列の最初、2番目、最後の項目を省略します.

    ネスト化アレイ破壊


    我々がオブジェクトの入れ子にされた破壊をすることができたように、我々は同様に配列で同じことをすることができます.以下のコード例を見てみましょう.
    //Const Color contains hex code and a nested array of rgb values
    const color = ['#FF00FF', [255, 0, 255]];
    
    // Use nested destructuring to assign red, green and blue
    const [hex, [red, green, blue]] = color;
    
    console.log(hex, red, green, blue); 
    //Output -> #FF00FF 255 0 255
    
    上の例では、RGB値は入れ子状に配列されており、四角形の括弧を使用してオブジェクトの破壊に似ています.

    混合破壊


    以下の例のような複雑なオブジェクトを扱う場合には、オブジェクト& array & nested destroyの両方のパワーを結合します.
    //Const Person contains nested elements of objects & arrays
    const person = {
      name: 'Skay',
      location: {
        city: 'Mumbai',
        country: 'India',
        latlong: [19.07609, 72.877426],
      },
    };
    
    // We are assigning 5 variables: name, country, city, lat, lng
    // We are combining object, nested object & array destructuring in a single line
    const {
      name,
      location: {
        city,
        country,
        latlong: [lat, lng],
      },
    } = person;
    
    console.log(
      `I am ${name} from ${city}, ${country}. Latitude(${lat}), Longitude(${lng})`
    );
    
    // Output -> I am Skay from Mumbai, India. Latitude(19.07609), Longitude(72.877426)
    
    注意事項
  • ' name '変数は、オブジェクトの破壊を使用して割り当てられます.それは'人'オブジェクトの直接の子です.
  • 変数' city '、' country 'と' Latlong 'はネストされた破壊を使用してアクセスされます.
  • ' Person 'オブジェクト内の' Latlong 'は、配列の破壊構文を使用してさらに破壊され、' LAT 'と' LONG '変数に割り当てられた配列です.
  • 関数の破壊-


    反応を使用している人とReactJs学習に入る人のために、これは少し静かに観察する1つのことです.以下のコード例に示すように、関数のパラメータに破壊を適用することができます.
    //Employee Object containing nested elements
    const employee = {
      name: 'Skay',
      age: 38,
      skills: {
        languages: 'JavaScript, HTML, CSS',
        databases: 'MySQL, PostgreSQL, MongoDB',
      },
    };
    
    //The person object is destructured within the parameters of the function that is passed in
    //We have used both object & nested object destructuring within the function parameters
    function displayEmployeeInfo({ name, age, skills: { languages, databases } }) {
      console.log(
        `The employee name is ${name} & his age is ${age}. He knows the following languages - ${languages} and is familiar with the databases - ${databases}`
      );
    }
    
    //We are invoking the function displayEmployeeInfo & passing in the 'employee' object
    displayEmployeeInfo(employee);
    //Output -> The employee name is Skay & his age is 38. He knows the following 
    //languages - JavaScript, HTML, CSS and is familiar with the databases - MySQL, 
    //PostgreSQL, MongoDB
    
    上の例では、「従業員」オブジェクトが破壊されて(入れ子破壊も適用されます)、関数' DisplayMethodInfo 'のパラメタの中で変数名、年齢、言語とデータベースが割り当てられます.
    「破壊されたパラメタ」が省略されるならば、それはエラーを投げます.上記の例では、DisplayMethodInfo ()を使用して従業員オブジェクトを渡さずにエラーをスローします.
    //Invoking the displayEmployeeInfo() without a function will output the error
    displayEmployeeInfo();
    
    //Output -> Uncaught TypeError: Cannot destructure property 'name' of 'undefined' as 
    //it is undefined.
    
    エラーを処理するためにデフォルト値としてfallbackオブジェクトリテラルを割り当てることができます.したがって、上記のコード例では、パラメータなしで呼び出される関数を処理するために以下に変更する必要があります.
    //Employee Object
    const employee = {
      name: 'Skay',
      age: 38,
      skills: {
        languages: 'JavaScript, HTML, CSS',
        databases: 'MySQL, PostgreSQL, MongoDB',
      },
    };
    
    //Object destructuring and nested object destructuring with default value of object literal
    function displayEmployeeInfo({
      name,
      age,
      skills: { languages, databases } = {},
    } = {}) {
      console.log(
        `The employee name is ${name} & his age is ${age}. He knows the following languages - ${languages} and is familiar with the databases - ${databases}`
      );
    }
    
    //Invoke the displayEmployeeInfo() without passing in the employee object
    displayEmployeeInfo();
    
    //Output -> The employee name is undefined & his age is undefined. 
    //He knows the following languages - undefined and is familiar with the databases - undefined
    
    デフォルトのオブジェクトリテラル{ {}'を指定すると、関数呼び出しを優雅に扱います.

    結論


    JavaScriptの破壊について知っているすべてをカバーしていると思います.保守性と読みやすさを向上させる強力な機能だと思います.また、入れ子になった変数にアクセスするために長いステートメントを入力する繰り返しを減らします.
    要約すると、この記事では以下のような破壊概念があります.
    物を破壊しているオブジェクト
  • ネストした破壊
  • を破壊しているアレイ
    の機能破壊
  • 混合爆破
  • 私はあなたが記事を楽しんでほしい.いつものように、私はあなたのコメント&フィードバックを知っているし、お友達と共有してください.
    次のことにも興味があります.