[removed] using tuples as dictionary keys

前端 未结 4 1961
-上瘾入骨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条回答
  •  旧时难觅i
    2021-02-06 23:22

    All object keys in Javascript are strings. Using my_map[[a,b]] = c will produce a key in my_map which is the result of [a,b].toString(): a.toString() + ',' + b.toString(). This may actually be desirable (and is similar to your use of a + ':' + b), but you may run into conflicts if your keys contain the separator (either the comma if you use the array as the key, or the colon if you write the string as you have in your example).

    Edit: An alternate approach would be to keep a separate array for key references. Eg:

    var keys = [
        [a,b],
        [c,d]
    ];
    var my_map = {
        'keys[0]': /* Whatever [a,b] ought to be the key for */,
        'keys[1]': /* Whatever [c,d] ought to be the key for */
    };
    

提交回复
热议问题