简体   繁体   中英

Using an array as a key for a dictionary in javascript

What is the best way, in Javascript, to use an array as a key that I can match against to get a value?

What I want to be able to do is get a value that may map to multiple keys.

Using a switch it would look like this:

switch(item)
{
    case "table": // fall through
    case "desk": // fall through
    case "chair": // fall through
        result = "office"
        break
}

in my head the syntax would be:

if (dict[0].key.contains(item)) return dict[0].value

I don't want to use a switch as the keys and values need to be dynamically allocated.

At the moment I am setting up an object which has two different arrays which need to stay synchronized in order to return the right values, which seems less than ideal.

var grammar =
[
{
    "app": "sms",
    "items":
    [
        [ "message","sms", "send"],
        [ "view", "read"]
    ],
    "terms":
    [
        [ "who+contact", "message+text" ],
        [ "who+contact"]
    ]
},
{
...
}
];

here if I get a match to "message", "sms" or "send" I return "who+contact,message+text", if I get a match to "view" or "read" I return "who+contact"

Thanks for any ideas.

Why can't you just use a normal object?

var store = {
    "table":"office",
    "desk":"office",
    "chair":"office"
};

console.log(store["desk"]);

If the problem is duplication, you can make the value a reference type.

var office = {value:"office"};
var store = {
    "table":office,
    "desk":office,
    "chair":office
};
var terms = [
    0           : [ "who+contact" , "message+text"],
    "whatever"  : [ "who+contact" ]
];

var items = [
    "message" : 0,
    "sms"     : 0,
    "send"    : 0,
    "view"    : "whatever",
    "read"    : "whatever"
];


function getTerm(match) {
    if (item[match]!==null) {
      return terms[ items[match] ];
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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