简体   繁体   English

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

[英]Using tuple as a key in a dictionary in javascript

In python I have a Random dictionary where I use tuple as a key and each is mapped to some value.在 python 中,我有一个 Random 字典,我使用元组作为键,每个字典都映射到某个值。

Sample样本

Random_Dict = {
    (4, 2): 1,
    (2, 1): 3,
    (2, 0): 7,
    (1, 0): 8
}

example in above key: (4,2) value: 1上面键中的示例:(4,2) 值:1

I am attempting to replicate this in Javascript world我试图在 Javascript 世界中复制这个

This is what I came up with这是我想出的

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

I am wondering if this is the most effective way.我想知道这是否是最有效的方法。 I almost wonder if i should do something like holding two numbers in one variable so that way i can have a dictionary in JS that maps 1:1.我几乎想知道我是否应该做一些事情,比如在一个变量中保存两个数字,这样我就可以在 JS 中拥有一个映射 1:1 的字典。 Looking for suggestions and solutions that are better寻找更好的建议和解决方案

You can use a Map to map sets of 2 arbitrary values.您可以使用Map映射2 个任意值的集合。 In the following snippet the keys can be 'tuples' (1), or any other data type, and the values can be as well:在以下代码段中,键可以是“元组”(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:因此,对于上面的示例,以下日志undefined ,尽管给定的“键”也是形状[4, 2]的数组,就像 Map 键之一一样:

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

(1) Tuples don't technically exist in Javascript. (1) 从技术上讲,Javascript 中不存在元组。 The closest thing is an array with 2 values, as I used in my example.最接近的是一个有 2 个值的数组,就像我在我的例子中使用的那样。

You can do it this way:你可以这样做:

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

[] in objects property is used for dynamic property assigning.对象属性中的[]用于动态属性分配。 So you can put an array in it.所以你可以在里面放一个数组。 So your property will become like [ [4,2] ] and your object key is [4,2] .所以你的属性会变成[ [4,2] ]并且你的对象键是[4,2]

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

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