簡體   English   中英

在 javascript 中使用數組作為字典的鍵

[英]Using an array as a key for a dictionary in javascript

在 Javascript 中,使用數組作為我可以匹配以獲取值的鍵的最佳方法是什么?

我想要做的是獲得一個可能 map 到多個鍵的值。

使用開關它看起來像這樣:

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

在我看來,語法是:

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

我不想使用開關,因為鍵和值需要動態分配。

目前我正在設置一個 object,它有兩個不同的 arrays 需要保持同步才能返回正確的值,這似乎不太理想。

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

在這里,如果我匹配到“message”、“sms”或“send”,我會返回“who+contact,message+text”,如果我匹配到“view”或“read”,我會返回“who+contact”

感謝您的任何想法。

為什么不能只使用普通的 object?

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

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

如果問題是重復,您可以將值設為引用類型。

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