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.

連想配列について

Last updated at Posted at 2022-02-09

JavaScriptの連想配列

JavaSciptには連想配列というものがあります。

連想配列とは

連想配列とはキーと値のペアで構成される配列です。JavaScriptではオブジェクトとして扱います。
ここの「キーと値のペア」はプロパティと呼びます。プロパティは値に関数を指定することもできます。

連想配列の宣言の仕方

sample.js
const foods = new Object();
const foods = {};

とうすることで宣言が完了します。

sample.js
const foods = {curry: "甘口",curry1: '中辛', curry2:"辛口"};

console.log(foods["curry"]);//甘口が表示
console.log(foods["curry1"]);//中辛が表示
console.log(foods["curry2"]);//辛口が表示

連想配列の配列の追加

sample.js
const foods = {curry: "甘口",curry1: '中辛', curry2:"辛口"};
foods["curry3"] = "激辛";

console.log(foods["curry3"])//激辛
console.log(foods);//Object { curry: "甘口", curry1: "中辛", curry2: "辛口", curry3: "激辛" }

このようにfoodsの変数の中にはcurry3の激辛が追加され、コンソールに中には表示されていることが確認できます。

連想配列の要素を更新

sample.js
const foods = {curry1: "甘口",curry2: "中辛",curry3:"辛口"};
foods["curry3"] = "激辛";

console.log(foods);//Object {curry1: "甘口",curry2:中辛,curry3:"激辛"}

更新したい値のkeyを指定することで辛口から激辛に変更されているが分かります。

連想配列の要素の削除

sample.js
const foods = {curry1: "甘口",curry2: "中辛",curry3:"辛口"};
delete foods["curry3"];

console.log(foods);//Object { curry1: "甘口",curry2:"中辛"}

deleteを使用し、削除を行います。コンソールには削除したいkeyのcurry3:辛口が削除されています。

連想配列の数を取得

sample.js
const foods = {curry1:"甘口",curry2:"中辛",curry3:"辛口"};
console.log(Object.keys(foods).length);//3

Object.keysメソッドを使用し、要素数を取得することができました。

連想配列をループで処理

sample.js
   var curry = {}
  for(var i=0; i<5; i++){
    curry["property" + i] = i * 100;
  }
  for(var key in curry) {
    if(curry.hasOwnProperty(key)) {
      var val = curry[key];
      console.log("key=", key, ", value=", val);
    }
  }
  console.log("property4の値は", curry.property4);

実行結果は以下のようになります。オブジェクトをfor … in文でループ処理してプロパティの値を出力していることが確認できます。

// コンソールに出力
//"key=" "property0" ", value=" 0
//"key=" "property1" ", value=" 100
//"key=" "property2" ", value=" 200
//"key=" "property3" ", value=" 300
// "key=" "property4" ", value=" 400
// "property4の値は" 400

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?