JavaScriptにおける値の参照
概要
JavaScriptでは、値の参照と操作が重要な役割を果たします。この章では、オブジェクトや配列などの複合データ型の参照方法、およびプロパティへのアクセス方法について学びます。
目次
- オブジェクト(連想配列)とは
- プロパティへのアクセス
- 関数プロパティ(メソッド)
- 配列プロパティ
- オブジェクトの組み込みメソッド
in演算子- 練習問題
1. オブジェクト(連想配列)とは
- オブジェクトは、
{}で囲まれたキー(key)と値(value)のペアの集合です。 - キーは文字列またはシンボルで、値は任意のデータ型(数値、文字列、配列、関数、さらには他のオブジェクトなど)を持てます。
2. プロパティへのアクセス
- オブジェクトのプロパティにアクセスするには、ドット記法(
.)を使用します。 - 例:
person.name、person.mother.age
3. 関数プロパティ(メソッド)
- オブジェクト内の関数は、そのオブジェクトのメソッドとして扱われます。
- 例:
person.birthYear()は現在の年からpersonのageを引いて、生年を計算します。
4. 配列プロパティ
- オブジェクト内に配列を格納することができます。
- 例:
person.hobbyは趣味を格納した配列です。person.hobby[0]で最初の趣味にアクセスできます。
5. オブジェクトの組み込みメソッド
Object.keys(obj): オブジェクトのキーの配列を返します。Object.values(obj): オブジェクトの値の配列を返します。Object.entries(obj): キーと値のペアの配列を返します。Object.assign(target, ...sources): 一つまたは複数のソースオブジェクトからターゲットオブジェクトにプロパティをコピーします。
6. in 演算子
in演算子は、特定のプロパティがオブジェクトに存在するかどうかをチェックします。- 例:
'name' in personはtrueを返しますが、'job' in personはfalseを返します。
7. 練習問題
下記console.logの出力を答えよ
const person = {
name: 'John',
age: 24,
married: false,
hobby: ['running', 'reading', 'programming'],
mother: {
name: 'Catherine',
age: 50,
married: true
},
birthYear: () => {
const now = new Date()
return now.getFullYear() - person.age
}
}
console.log(person.name)
console.log(person.age)
console.log(person.married)
console.log(person.hobby)
console.log(person.hobby[0])
console.log(person.hobby.filter((v) => v === 'reading'))
console.log(person.hobby.filter((v) => v === 'reading')[0])
console.log(person.hobby.map((v) => v.replace(v[0], v[0].toUpperCase())))
console.log(person.mother.name)
console.log(person.mother.age)
console.log(person.birthYear())
console.log(Object.keys(person))
console.log(Object.values(person))
console.log(Object.entries(person))
// Object.assignは第一引数をObject.assignの計算結果で上書きする
console.log(Object.assign({ working: true }, person))
console.log(person)
console.log(Object.assign(person, { working: true }))
console.log(person)
console.log(Object.assign(person, { name: 'Bob' }, { name: 'Mike' }))
console.log(person)
console.log(Object.assign(person, { name: 'Bob', age: 30 }, { name: 'Mike' }))
console.log('name' in person)
console.log('job' in person)
練習問題の解答
以下に練習問題の各console.logステートメントの出力結果を示します。
console.log(person.name)=>Johnconsole.log(person.age)=>24console.log(person.married)=>falseconsole.log(person.hobby)=>['running', 'reading', 'programming']console.log(person.hobby[0])=>'running'console.log(person.hobby.filter((v) => v === 'reading'))=>['reading']console.log(person.hobby.filter((v) => v === 'reading')[0])=>'reading'console.log(person.hobby.map((v) => v.replace(v[0], v[0].toUpperCase())))=>['Running', 'Reading', 'Programming']console.log(person.mother.name)=>Catherineconsole.log(person.mother.age)=>50console.log(person.birthYear())=> Johnの生年 (現在年 - 24)