查找对象属性中的最大值

Finding the largest value among the properties of an object

我有以下任务

写一个 function findBestEmployee (employees),其中包含一个员工对象和 returns 最有效率的人(完成最多任务的人)的名字。员工和已完成任务的数量作为对象属性包含在 "name": "number of tasks".

格式中

我在下面的代码中显示错误:

The function is expected to return an empty string for an empty object. Can someone please help me.

const findBestEmployee = function (employees) {
    'use strict';
  
    let max = 0;
    let bestEmployee;

    for (const employee in employees) {
        const numberOfTasks = employees[employee];
        if (numberOfTasks > max) {
            max = numberOfTasks;
            bestEmployee = employee;
        }
    }

    return bestEmployee;
};

const developers = {
    ann: 29,
    david: 35,
    helen: 1,
    lorence: 99,
};
 
//console.log(findBestEmployee(developers)); 
// 'lorence'

const supports = {
    poly: 12,
    mango: 17,
    ajax: 4,
}; 
//console.log(findBestEmployee(supports)); 
// 'mango'

const sellers = {
    lux: 147,
    david: 21,
    kiwi: 19,
    chelsy: 38,
}
//console.log(findBestEmployee(sellers)); 
// 'lux'

将变量 bestEmployee 初始化为一个已知的无效值,最好 null。如果您从未将其设置为循环中的某个员工,它将保持 null。所以在函数的最后如果还是null,return一个空字符串:

const findBestEmployee = function (employees) {
    'use strict';
  
    let max = 0;
    let bestEmployee = null; // initialise

    for (const employee in employees) {
        const numberOfTasks = employees[employee];
        if (numberOfTasks > max) {
            max = numberOfTasks;
            bestEmployee = employee;
        }
    }

    // return empty string if still null
    return bestEmployee ? bestEmployee : '';
};