Javascript 在jQuery中通过索引获取字典的键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10894484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:28:16  来源:igfitidea点击:

Get key value of dictionary by index in jQuery

javascriptjquerydictionaryjavascript-objects

提问by Kassem

I have a javascript dictionary object which has a pre-set keys that are defaulted to 0. Then I need to loop through the elements of this dictionary by indexand use the value of the key to set its value. Below is my code to make things easier to understand:

我有一个 javascript 字典对象,它有一个默认为0. 然后我需要通过索引遍历这个字典的元素并使用键的值来设置它的值。下面是我的代码,使事情更容易理解:

var _map = {
    'severity-normal': 0,
    'severity-minimal': 0,
    'severity-moderate': 0,
    'severity-severe': 0,
    'severity-highly-severe': 0
};

    mapSeverities: function () {
        for (var i = 0; i < _map.length; i++) {
            //get the key value, ex: severity-normal, by index (which would by i)
            var key = //retrieved key value
            _map[key] = this.data(key);
        }
    }

In other words, suppose we're dealing with C#, I want to get the KeyValuePairat a certain index, then access its Keyand Valueproperties.

换句话说,假设我们正在处理 C#,我想KeyValuePair在某个索引处获取,然后访问它的KeyValue属性。

Any suggestions?

有什么建议?

采纳答案by xdazz

For object _map, you should use for .. in.

对于对象_map,您应该使用for .. in.

for (var key in _map) {
  _map[key] = this.data[key];
}

回答by Prasenjit Kumar Nag

You can also use $.eachlike this

你也可以$.each这样使用

$.each(_map, function(key, value) { 
  // key is the key
  // value is the value
});

Working Fiddle

工作小提琴