开发者

Using an array as a key for a dictionary in javascript

开发者 https://www.devze.com 2023-03-11 12:49 出处:网络
What is the best way, in Javascript, to use an array as a key that I can match against to get a value?

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开发者_Go百科 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消