0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[JS] オブジェクト

Posted at

定義方法

{ } = オブジェクトリテラル

初期化を行なってからプロパティを格納する

const person = { };
person.name = 'shun';

初期化を行なうタイミングでプロパティを格納する

const person = {
  name: 'shun'
};

オブジェクトの中にオブジェクトを格納したり、配列を格納することもできます。

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  }
};

ドット記法

person.color;のような記法を「ドット記法」と言い、値を取得できる

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  }
};

console.log(person.color);

Image from Gyazo


値を変更する

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  }
};

person.age = 12
console.log(person.age);

Image from Gyazo

ブラケット記法

[ ]で書く記法

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  }
};

person['age'] = 12
console.log(person.age);

Image from Gyazo


ブラケット記法は、変数を使いたい場合に使用します

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  }
};

const agekey = 'age'
person[agekey] = 12
console.log(person.age);

Image from Gyazo

キー情報が動的な場合に、意図して[ ]を使うことがあります

メソッドの格納

オブジェクトはメソッドも格納することができます

const person = {
  name: 'shun',
  age: 20,
  gender: 'male',
  color: ['white', 'black'],
  interests: {
    sports: 'soccer',
    music: 'King Gnu'
  },
  getFullColor: function() {
    console.log(this.color[0] + this.color[1])
  }
};

const agekey = 'age'
person[agekey] = 12
console.log(person.age);
person.getFullColor();

Image from Gyazo

thisオブジェクトは、宣言されたオブジェクトのこと(今回だったらperson)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?