在javascript中获取键值对中的最大键

时间:2016-12-28 08:37:51

标签: javascript

请考虑此键值对:

var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "1",
                    "100": "4",
                    "101": "0"}

我想获得最高价值,在这个例子中是:101。

我怎么能这样做?

由于

更新1:

我使用此代码:Fast way to get the min/max values among properties of objectGetting key with the highest value from object

但两者都返回Max Value或comapre值

5 个答案:

答案 0 :(得分:8)

来自MDN的好例子:

var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "3",
                    "100": "4",
                    "101": "5"}
                    
                    
function getMax(obj) {
  return Math.max.apply(null,Object.keys(obj));
}
console.log(getMax(dict_Numbers));

答案 1 :(得分:7)

将容易找到的Getting key with the highest value from object应用于键,注意字符串

var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "3",
                    "100": "4",
                    "101": "5"}

console.log(Object.keys(dict_Numbers).reduce(
  function(a, b){ 
    return parseInt(a,10) > parseInt(b,10) ? a : b 
  })
);

但是正如我对这个问题发表评论的那样,在sinisake发布的Object.keys上使用Math.max有一种更简洁的方法。

答案 2 :(得分:2)



var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "3",
                    "100": "4",
                    "101": "5"}

console.log(Math.max(...Object.keys(dict_Numbers)));




请注意,此代码使用ES6功能。

答案 3 :(得分:1)

试试这个。

您可以迭代对象的属性并检查其值。



var dict_Numbers = {
  "96": "0",
  "97": "1",
  "98": "2",
  "99": "3",
  "100": "4",
  "101": "5"
};

var max = 0;

for (var property in dict_Numbers) {
  max = (max < parseFloat(property)) ? parseFloat(property) : max;
}

console.log(max);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;