简体   繁体   English

在 javascript 中使用数组作为字典的键

[英]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?在 Javascript 中,使用数组作为我可以匹配以获取值的键的最佳方法是什么?

What I want to be able to do is get a value that may map to multiple keys.我想要做的是获得一个可能 map 到多个键的值。

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.目前我正在设置一个 object,它有两个不同的 arrays 需要保持同步才能返回正确的值,这似乎不太理想。

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"在这里,如果我匹配到“message”、“sms”或“send”,我会返回“who+contact,message+text”,如果我匹配到“view”或“read”,我会返回“who+contact”

Thanks for any ideas.感谢您的任何想法。

Why can't you just use a normal object?为什么不能只使用普通的 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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