问题描述
我遇到一种情况,我想创建一个从元组到整数的映射.在python中,我将简单地使用元组(a,b)
作为字典的键
I have a situation where I want to create a mapping from a tuple to an integer. In python, I would simply use a tuple (a,b)
as the key to a dictionary,
JavaScript是否有元组?我发现javascript中的(a,b)
作为表达式仅返回b(最后一项).显然,这是从C继承的.
Does Javascript have tuples? I found that (a,b)
in javascript as an expression just returns b (the last item). Apparently this is inherited from C.
因此,作为一种解决方法,我认为我可以改用数组,
So, as a workaround, I thought I can use arrays instead,
my_map[[a,b]] = c
我在Firebug控制台上尝试了它,它似乎起作用了.这是个好方法吗?
I tried it at the Firebug console and it seemed to work. Is that a good way to do it?
我想到的另一种选择是从元组中创建一个字符串
Another alternative I thought of is to create a string out of the tuples
my_map[""+a+":"+b] = c
所以问题是:这些方法中的任何一个是否存在问题?有更好的方法吗?
So the question is: is there any problem with any of these methods? Is there a better way?
小澄清:在我的情况下,a,b,c都是整数
Small clarification: in my case, a,b,c are all integers
推荐答案
EcmaScript不会区分按名称或按[]
索引属性,例如.
EcmaScript doesn't distinguish between indexing a property by name or by []
, eg.
a.name
从字面上等同于
a["name"]
唯一的区别是数字等在命名属性访问中不是有效的语法
The only difference is that numbers, etc are not valid syntax in a named property access
a.1
a.true
等等都是无效的语法.
所有这些索引编制机制都相同的原因是,在EcmaScript中, all 属性名称都是字符串.例如.
Alas the reason all of these indexing mechanisms are the same is because in EcmaScript all property names are strings. eg.
a[1]
有效地解释为
a[String(1)]
在您的示例中,这意味着您要做:
Which means in your example you do:
my_map[[a,b]] = c
成为哪个人
my_map[String([a,b])] = c
与第二个示例在本质上是相同的(但是取决于实现,它可能会更快).
Which is essentially the same as what your second example is doing (depending on implementation it may be faster however).
如果您想要真正的与值相关的查询,则需要在js语言之上自己实现它,并且您将失去漂亮的[]样式访问权限:-(
If you want true value-associative lookups you will need to implement it yourself on top of the js language, and you'll lose the nice [] style access :-(
这篇关于Javascript:使用元组作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!