尝试遍历对象并找到具有最大值的键 - 得到不准确的答案



试图在值中找到最大值,但总是得到不准确的值。我做错了什么?

const findBestEmployee = function(employees) {
let theBest = Object.values(employees)[0];
for (let [key, value] of Object.entries(employees)) {
if (value > theBest){
theBest = value
}
return key
}
};

console.log(
findBestEmployee({
ann: 29,
david: 35,
helen: 1,
lorence: 99,
})
);

输出annlorence- 我做错了什么?

您还必须维护密钥,然后在循环后返回最佳密钥。您将在循环的第一次运行时将其放入循环中来返回它。

const findBestEmployee = function(employees) {
let theBest = Object.values(employees)[0];
let theBestKey = Object.keys(employees)[0];
for (let [key, value] of Object.entries(employees)) {
if (value > theBest){
theBest = value;
theBestkey = key;
}
}
return theBestkey;
};

您返回for循环中的值,因此第一项始终作为bestEmployee返回。

const findBestEmployee = function(employees) {
let bestPerformance = Object.values(employees)[0];
let bestEmployeeName = Object.values(employees)[1];
for (let [name, performance] of Object.entries(employees)) {
if (performance > bestPerformance) {
bestPerformance = performance;
bestEmployeeName = name;
}
}
return bestEmployeeName;
};
console.log(
findBestEmployee({
ann: 29,
david: 35,
helen: 1,
lorence: 99,
}),
);
// lorence

还有另一种方法,基于Array.prototype.reduce()

const employees = {ann:29,david:35,helen:1,lorence:99},
getKeyOfMax = obj => 
Object
.keys(obj)
.reduce((r,key) => 
obj[key]>obj[r] ? key : r)

console.log(getKeyOfMax(employees))
.as-console-wrapper{min-height:100%;}

最新更新