在JavaScript中使用元组作为字典键

8
在Python中,我有一个随机字典,其中使用元组作为键,并且每个元组映射到某个值。
样例
Random_Dict = {
    (4, 2): 1,
    (2, 1): 3,
    (2, 0): 7,
    (1, 0): 8
}

以上示例中的键:(4,2) 值:1

我正在尝试在Javascript世界中复制此内容

这是我想出来的

const randomKeys = [[4, 2], [2, 1], [2, 0], [1, 0] ]

const randomMap = {}

randomMap[randomKeys[0]] = 1
randomMap[randomKeys[1]] = 3
randomMap[randomKeys[2]] = 7
randomMap[randomKeys[3]] = 8
randomMap[[1, 2]] = 3

我在想这是否是最有效的方法。我甚至在考虑是否应该使用一个变量来保存两个数字,这样我就可以在JS中使用字典进行1:1映射。寻求更好的建议和解决方案。


3
请注意,例如 [1, 2] 的实际键名应为 "1,2";非字符串键名会被转换为字符串。 - jonrsharpe
你想要什么数据结构? - Nina Scholz
在Python中,我可以使用元组作为键来创建一个字典。这就是我正在寻找的。 - Dinero
对于这种情况,我通常发现创建一个类,比如“TupleKeyDict”,并使用add/get方法来模仿Python中的行为更好。 - user2263572
“tuple” 不是 JavaScript 的一种类型。你知道它的等价物吗? - Nina Scholz
2个回答

5

您可以使用Map来将 2 个任意值进行映射。在下面的代码片段中,键可以是 '元组'(1),或者任何其他数据类型,值也可以是:

const values = [
  [ [4, 2], 1],
  [ [2, 1], 3],
  [ [2, 0], 7],
  [ [1, 0], 9],
];

const map = new Map(values);


// Get the number corresponding a specific 'tuple'
console.log(
  map.get(values[0][0]) // should log 1
);

// Another try:
console.log(
  map.get(values[2][0]) // should log 7
);

Note that the key equality check is done by reference, not by value equivalence. So the following logs undefined for the above example, although the given 'key' is also an array of the shape [4, 2] just like one of the Map keys:

console.log(map.get([4, 2]));

(1)在JavaScript中,元组(tuples)不存在。最接近的东西是具有2个值的数组,正如我在示例中使用的那样。


1
看起来不错,我想知道为什么我的问题被踩了。我没有问错任何事情,我甚至提供了我的解决方案。 - Dinero
我点赞了它,我对于三元组也有同样的问题,这个解决方案很有效! - Melvin Roest

4

你可以这样做:

const randomKeys = {
    [[4, 2]]: 1,
    [[2, 1]]: 3,
    [[2, 0]]: 7,
    [[1, 0]]: 8
}

console.log(randomKeys[ [4,2] ]) // 1 

[] 在对象属性中用于动态属性分配。因此,您可以将其放入一个数组中。您的属性将变得像这样:[[4,2]],而您的对象键是[4,2]


虽然很不专业,但仍然相当酷。 - Melvin Roest
请注意,将值用作对象键会将其转换为字符串,这可能会导致歧义。例如,如果您的元组包含带有逗号的字符串,则可能会出现问题。 - vpzomtrrfrt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接