如何使用 JavaScript/JQuery 创建一个简单的映射

2022-08-30 01:25:27

如何创建与此 Java 代码等效的 JavaScript/JQuery:

Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times

function Object get(k) {
    return map.get(k);
}

答案 1

编辑:过时的答案,ECMAScript 2015(ES6)标准javascript有一个Map实现,请阅读此处以获取更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

答案 2

只需使用普通对象:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}