简体   繁体   English

Javascript对象/数组作为Map的键

[英]Javascript object/array as key for Map

What's the best way to use 2 string variables as the key for a Map ? 将2个字符串变量用作Map的键的最佳方法是什么?

const map = new Map();
map.set(['a', 'b'], 5);
map.get(['a', 'b']); //undefined

Creating a reference to [v1, v2] and using that as key is not an option for my case. 创建对[v1, v2]的引用并将其用作键不是我的情况的选择。

Is the only option to combine the two variables with a delimiter? 将两个变量与定界符组合在一起的唯一选择是吗? (will be messy if the string variables can potentially contain the delimiter character). (如果字符串变量可能包含定界符,则会很混乱)。

May nest the Map: 可能会嵌套地图:

var map=new Map();

function set(key1,key2,value){
  if(map.has(key1)){
    return map.get(key1).set(key2,value);
  }
  return map.set(key1,new Map([[key2,value]]));
}

function get(key1,key2){
 if(map.has(key1)){
  return map.get(key1).get(key2);
 }
 return false;
}

set("a","b","value");
console.log(get("a","b"))

If you want a variable length of keys, you may recursively create Maps and add an exit delimiter at the end, probably a symbol: 如果您想要可变长度的键,则可以递归创建Maps并在末尾添加出口定界符 ,可能是一个符号:

var exit=Symbol("exit");
set("a",exit,"value");
set("a","b",exit,"value");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM