Help us understand the problem. What is going on with this article?

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

連想配列

連想配列は普通の配列と違い、数字だけでなく文字列も添字にして使うことができます。連想配列の添字は、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の説明

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした