在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的字典。寻找建议和解决方案 更好
您可以使用^{} 映射两个任意值的集合。在以下代码段中,键可以是“元组”(1)或任何其他数据类型,值也可以是:
(1)从技术上讲,Javascript中不存在元组。最接近的是一个具有2个值的数组,正如我在示例中使用的那样
您可以这样做:
对象属性中的
[]
用于动态属性分配。所以你可以在里面放一个数组。因此,您的属性将变得像[ [4,2] ]
,而您的对象键是[4,2]