【问题标题】:Using an array as a key for a dictionary in javascript在javascript中使用数组作为字典的键
【发布时间】:2011-06-07 19:42:48
【问题描述】:

在 Javascript 中,使用数组作为我可以匹配以获取值的键的最佳方法是什么?

我想要做的是获得一个可以映射到多个键的值。

使用开关它看起来像这样:

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

我不想使用开关,因为键和值需要动态分配。

目前我正在设置一个对象,它有两个不同的数组,它们需要保持同步才能返回正确的值,这似乎不太理想。

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 +联系人”

感谢您的任何想法。

【问题讨论】:

    标签: javascript arrays dictionary


    【解决方案1】:

    为什么不能只使用普通对象?

    var store = {
        "table":"office",
        "desk":"office",
        "chair":"office"
    };
    
    console.log(store["desk"]);
    

    如果问题是重复,可以将值设为引用类型。

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

    【讨论】:

      【解决方案2】:
      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;
      }
      

      【讨论】:

      • 似乎没有比这种方式更好的答案了,所以到目前为止我一直在使用这个答案。谢谢。
      猜你喜欢
      • 2020-06-17
      • 2010-11-28
      • 2013-08-29
      • 2020-09-25
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多