简体   繁体   English

在对象属性中找到最大的数字

[英]Finding the biggest number in Object Properties

I have a simple JS object literal, which gains a property.我有一个简单的 JS 对象文字,它获得了一个属性。 I cannot figure out the math, or method of looking at the properties, selecting the highest value from the properties, and then displaying only that key.我无法弄清楚查看属性的数学方法或方法,从属性中选择最高值,然后仅显示该键。

var president = {"FDR":1,"Lincoln":2,"Buchanan":43,"Hoover":34};
    president.Obama = 3;
var x;
var txt = "";
for (x in president) {
  txt += president[x] + " ";
}
console.log(president);

I have seen several ways of trying to get max number, in this case 43 but returning "Buchanan", but none of them work within the console I am using.我已经看到了几种尝试获得最大数量的方法,在这种情况下是 43,但返回“Buchanan”,但它们都没有在我使用的控制台中工作。 _.max gives me "_ is not defined." _.max给我“_ 未定义。” I tried a function call within the Math.max.apply method, and it gives me my initial list as the answer, but doesn't put the 5th president in that list.我在Math.max.apply方法中尝试了一个函数调用,它给了我我的初始列表作为答案,但没有将第 5 任总统放在该列表中。

If anyone can give me some old school hard coding to take in the object properties, including the new property I added, while using the for in loop, I would greatly appreciate it.如果有人能给我一些老式的硬编码来接受对象属性,包括我添加的新属性,同时使用for in循环,我将不胜感激。 I can't find a good idea of how this is done.我无法找到如何做到这一点的好主意。

Try the following:请尝试以下操作:

 var president = {"FDR":1,"Lincoln":2,"Buchanan":43,"Hoover":34}; president.Obama = 3; max = -1; //initial value; pres = ""; //initial president for (x in president) { if(president[x] > max){ //if the value is greater than max pres = x; //set the new president max = president[x]; //set the new max } } console.log(pres);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM