在javascript中使用元组作为字典中的键

2024-09-30 04:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在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的字典。寻找建议和解决方案 更好


Tags: 方法示例字典世界样品数字randomjavascript
2条回答

您可以使用^{}映射两个任意值的集合。在以下代码段中,键可以是“元组”(1)或任何其他数据类型,值也可以是:

&13; 第13部分,;
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
);
和#13;
和#13;

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中不存在元组。最接近的是一个具有2个值的数组,正如我在示例中使用的那样

您可以这样做:

const randomKeys = {
    [[4, 2]]: 1,
    [[2, 1]]: 3,
    [[2, 0]]: 7,
    [[1, 0]]: 8
}
console.log(randomKeys[ [4,2] ]) // 1 

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

相关问题 更多 >

    热门问题