如何比较javascript中的对象元素值

如何比较javascript中的对象元素值

例如 :

var obj = { tom: "5000", justin: "500", linda: "3000" }; 

我可以怎样做一个代码来知道哪个人有更高的薪水,例如:我应该在这里得到结果(汤姆)?

您可以先用Object.keys获取对象的所有键,然后通过Array#reduce获取更高薪水键来Array#reduce

 var object = { tom: "5000", justin: "500", linda: "3000" }, keys = Object.keys(object), max = keys.reduce(function (a, b) { return +object[a] > +object[b] ? a : b; }); console.log(max); 
 function getMaxUser(object) { let maxUser = { max: 0 } for (let user in object) { if (maxUser.max < object[user]) { maxUser = { max: object[user], user: user } } } return maxUser } var obj = { tom: "5000", justin: "500", linda: "3000" } console.log(getMaxUser(object).user) //tom