連想配列

連想配列とは

通常の配列はインデックス番号で値を管理していますが、連想配列はわかりやすい名前などを付けて管理することができます。連想配列では、付けた名前(インデックス)のことをキーと呼びます。

連想配列の作成

var 連想配列名 = {

  キー名1:値,

  キー名2:値,

  キー名3:値,

}

連想配列の使用

<script>
var favorites = {
food : 'カレー',
color : '緑',
number : 7
};
favorites.sports = 'テニス'; //キーと値の追加
favorites.car = 'マツダアクセラ」';//キーと値の追加
document.write(favorites.food+'<br>');
document.write(favorites.color+'<br>');
document.write(favorites.number+'<br>');
document.write(favorites.sports+'<br>');
document.write(favorites.car+'<br><br>');

document.write(favorites['food']+'<br>');
document.write(favorites['color']+'<br>');
document.write(favorites['number']+'<br>');
document.write(favorites['sports']+'<br>');
document.write(favorites['car']+'<br><br>');


var favorites2 = {
'食べ物' : 'オムライス',
'色' : '青',
'数字' : 1
};
favorites2['スポーツ'] = 'テニス'; //キーと値の追加
favorites2['車'] = 'マツダアクセラ」'; //キーと値の追加
document.write(favorites2['食べ物']+'<br>');
document.write(favorites2['色']+'<br>');
document.write(favorites2['数字']+'<br>');
document.write(favorites2['スポーツ']+'<br>');
document.write(favorites2['車']+'<br>');
</script>

 

結果

f:id:develog:20160906100512g:plain