オブジェクトプロパティの管理
メニューを表示するにはスワイプしてください
オブジェクトのプロパティ操作に関する3つの重要な概念を確認します:
- プロパティ値の変更
- 新しいプロパティの追加
- 省略記法プロパティの使用
プロパティ値の変更
オブジェクトが作成された後、そのプロパティは簡単に更新できます。 値を変更するには、ドット記法を使用して目的のプロパティに新しい値を代入します。
12345678910111213141516const company = { title: "Toyota", nativeName: "トヨタ自動車株式会社", industry: "Pharmacy", founded: { year: 1996, month: "August", day: 28, }, }; company.industry = "Automotive"; company.founded.year = 1937; console.log(company.industry); // Output: Automotive console.log(company.founded.year); // Output: 1937
この例では、industry および founded.year プロパティの値を変更します。
新しいプロパティの追加
プロパティの追加は、既存のプロパティの変更と同じ方法で行います。 プロパティ名が存在しない場合、JavaScript は自動的に新しいプロパティを作成します。
1234567891011121314const company = { title: "Toyota", nativeName: "トヨタ自動車株式会社", industry: "Automotive", founded: { year: 1937, month: "August", day: 28, }, }; company.founder = "Kiichiro Toyoda"; console.log(company.founder); // Output: Kiichiro Toyoda
この例では、founder オブジェクトに新しいプロパティ company を追加します。
ショートハンドプロパティの利用
ショートハンドプロパティを使うことで、より簡潔にオブジェクトを作成可能。 プロパティ名と変数名が同じ場合、JavaScript では繰り返しを省略できます。
12345678910const name = "Carl Benz"; const birthCountry = "Germany"; const person = { name: name, birthCountry: birthCountry, }; console.log(person.name); // Output: Carl Benz console.log(person.birthCountry); // Output: Germany
省略記法を使用すると、同じオブジェクトをより簡潔に作成可能。
12345678910const name = "Carl Benz"; const birthCountry = "Germany"; const person = { name, birthCountry, }; console.log(person.name); // Output: Carl Benz console.log(person.birthCountry); // Output: Germany
省略記法では、プロパティ名のみを指定し、値は同名の変数から自動的に取得。
1. オブジェクトを作成した後、そのプロパティの値をどのように変更できますか?
2. 存在しないプロパティの値をドット記法で変更しようとした場合、どうなりますか?
3. 次のうち、オブジェクト作成時に省略記法(ショートハンドプロパティ)を使用している例はどれですか?
4. ショートハンドプロパティを使用して、変数 city を userLocation のプロパティとしてどのように追加できますか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 7
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 7