[removed] using tuples as dictionary keys

前端 未结 4 1956
-上瘾入骨i
-上瘾入骨i 2021-02-06 23:21

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,

Does

4条回答
  •  别跟我提以往
    2021-02-06 23:29

    EcmaScript doesn't distinguish between indexing a property by name or by [], eg.

    a.name
    

    is literally equivalent to

    a["name"]
    

    The only difference is that numbers, etc are not valid syntax in a named property access

    a.1
    a.true
    

    and so on are all invalid syntax.

    Alas the reason all of these indexing mechanisms are the same is because in EcmaScript all property names are strings. eg.

    a[1]
    

    is effectively interpreted as

    a[String(1)]
    

    Which means in your example you do:

    my_map[[a,b]] = c
    

    Which becomes

    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).

    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 :-(

提交回复
热议问题