通过密钥从JavaScript获取字典值

时间:2017-09-10 17:17:35

标签: javascript jquery

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 个答案:

答案 0 :(得分:4)

而不是使用数组使用对象

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

答案 1 :(得分:0)

变量字典是由对象组成的数组。如果您想要访问,则需要通过索引访问。

<强>样本

&#13;
&#13;
 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);
}
&#13;
&#13;
&#13;