破壊を理解する
42077 ワード
導入
破壊は、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つの主なものがあります.
//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
*/
破壊は何か
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
*/
注意するカップル
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
*/
オブジェクトの破壊
上記のコードスニペットは、オブジェクトの破壊の例です.別の例を見てみましょう.そうすれば、私たちは本当にその概念を強化することができます.
//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
注意事項
最初に、値「名前」、「年齢」と「技術」は『従業員』オブジェクトから破壊されました.
//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
デフォルト値
破壊中に変数にデフォルト値を割り当てることができます.そうすることができないので、値'未定義'は破壊された変数に割り当てられます.
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
注意事項
// 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
デフォルト値
我々がオブジェクト破壊にデフォルト値代入をする方法のように、我々は同様に配列破壊のためにすることができます.
// 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)
注意事項
//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)
関数の破壊-
反応を使用している人と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の破壊について知っているすべてをカバーしていると思います.保守性と読みやすさを向上させる強力な機能だと思います.また、入れ子になった変数にアクセスするために長いステートメントを入力する繰り返しを減らします.
要約すると、この記事では以下のような破壊概念があります.
物を破壊しているオブジェクト
//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
//Invoking the displayEmployeeInfo() without a function will output the error
displayEmployeeInfo();
//Output -> Uncaught TypeError: Cannot destructure property 'name' of 'undefined' as
//it is undefined.
//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の破壊について知っているすべてをカバーしていると思います.保守性と読みやすさを向上させる強力な機能だと思います.また、入れ子になった変数にアクセスするために長いステートメントを入力する繰り返しを減らします.
要約すると、この記事では以下のような破壊概念があります.
物を破壊しているオブジェクト
の機能破壊
次のことにも興味があります.
Reference
この問題について(破壊を理解する), 我々は、より多くの情報をここで見つけました https://dev.to/skaytech/es6-understanding-destructuring-49npテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol