代码之家  ›  专栏  ›  技术社区  ›  maciejka

通过键从JavaScript中的字典中获取值

  •  3
  • maciejka  · 技术社区  · 7 年前

    JavaScript 脚本我创建了以下字典。

    var dictionary =[];
    $(function () {
      dictionary.push({
        key: @item.Key.ToShortDateString().ToString(),
        value: @Html.Raw(JsonConvert.SerializeObject(item.Value)),
      });
      alert(dictionary['2017-09-19']);
    });
    

    它提醒我 undefined . 我怎样才能从这本字典中读出价值?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Dan Philip Bejoy    7 年前

    使用对象而不是使用数组

    $(function () {
      var dictionary = {};
      dictionary[@item.Key.ToShortDateString().ToString()] = @Html.Raw(JsonConvert.SerializeObject(item.Value));
      alert(dictionary['2017-09-19']);
    });
    
        2
  •  1
  •   Sajeetharan    7 年前

    变量字典是由对象组成的数组。如果你想访问,你需要按索引访问。

    演示

     var dictionary = [];
     dictionary.push({
        key: '2017-09-19',
        value: 'test',
      });
    var result = dictionary.filter(function(element) {
        return element.key == '2017-09-19';
    });
    
    if (result.length > 0) {
        // we have found a corresponding element
         console.log(result[0].value);
    }