0
2

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 5 years have passed since last update.

JavaScriptで連想配列をつくる方法

Posted at

連想配列

連想配列は普通の配列と違い、数字だけでなく文字列も添字にして使うことができます。連想配列の添字は、keyと言います。
JavaScriptでは、Mapオブジェクトを提供しているので、それを使います。

const myMap = new Map();

let keyString = "文字列",
    keyObj = {},
    keyFunc = function() {};

// 値を設定(追加)する
myMap.set(keyString, "'文字列' と関連付けられた値");
myMap.set(keyObj, "keyObj と関連付けられた値");
myMap.set(keyFunc, "keyFunc と関連付けられた値");

myMap.size; // 3

// 値を取得する(取り出す)
myMap.get(keyString);    // "'文字列' と関連付けられた値"
myMap.get(keyObj);       // "keyObj と関連付けられた値"
myMap.get(keyFunc);      // "keyFunc と関連付けられた値"

また、for...of...ループを使用して反復処理を行うこともできます。

const myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (let [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one

また、Array.fromを使えば、連想配列を普通の配列にすることもできます。
ただし、配列の中に配列があるようになります。

const myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
let mapArray = Array.from(myMap);
console.log(mapArray);
//[['0', 'Zero'], ['1', 'one']]

console.log(mapArray[0]);
//[ 0, 'zero' ]

//キーを取り出す。
let mapKey = Array.from(myMap.keys());
console.log(mapKey);
// ['0', '1'];

//値を取り出す。
let mapValue = Array.from(myMap.values());
console.log(mapValue);
// ['Zero', 'one'];

参考・引用:MDN Mapの説明

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?