clover.blue

[JS講座] 8. 連想配列(Object)

Data
2020/02/19
Tag

連想配列の宣言

const empty = {};
const fruits = {
  red: 'りんご',
  orange: 'みかん',
  yellow: 'バナナ'
};

※ 左側のred, orange, yellowの部分を添字といいます。

連想配列の取り出し方

  1. 変数名.添字
  2. 変数名['添字']

※ 2だと添字部分を変数にできるので 、うまい具合に使い分けましょう。

console.log(fruits.red); // りんご
console.log(fruits['orange']); // みかん

const color = 'yellow'
console.log(fruits[color]); // バナナ

連想配列と多次元配列を使って整理

const fruits = {
  red: ['りんご', 'さくらんぼ', 'いちご'], // 赤い果物
  orange: ['かき', 'みかん', 'びわ'], // オレンジ色果物
  yellow: ['バナナ', 'パイナップル', 'レモン'] // 黄色い果物
};

取り出し方

console.log(fruits.red[0]); // りんご
console.log(fruits\['orange'\][1]); // みかん

const color = 'yellow'
console.log(fruits\[color\][0]); // バナナ

[デモ]連想配列(Object)