Javascript 减少未定义的返回

Javascript 减少未定义的返回,javascript,undefined,reduce,Javascript,Undefined,Reduce,我有一组对象(汽车): 还有一个函数可以返回阵列中最快的汽车: function getFastestCar(cars) { cars.reduce(function (prevFastestCar,curFastestcar) { if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar; else return prevFastestCar; }, {speed: -

我有一组对象(汽车):

还有一个函数可以返回阵列中最快的汽车:

function getFastestCar(cars) {
   cars.reduce(function (prevFastestCar,curFastestcar) {
       if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
       else return prevFastestCar;
   }, {speed: -Infinity, name: "test"});
};

搜索了几个小时后,我找不到函数返回未定义的任何解决方案。我调试了代码,该函数运行得非常好,除了在最后一个“步骤”中,它以某种方式将最快的汽车替换为未定义的汽车。我试图理解reduce方法背后的概念,我知道有更简单的方法可以做到这一点,但我很好奇为什么它不能正常工作。

您需要
从函数中返回减少的值

返回车辆。减少(…)

请参见的说明

返回值

由减少产生的值


您需要
返回函数中的减少值

返回车辆。减少(…)

请参见的说明

返回值

由减少产生的值


这可能只是个人喜好,但我不喜欢在涉及比较的任务中使用Array.reduce。我认为以下几点更容易理解:

const cars=[
{速度:20,颜色:“红色”},
{速度:5,颜色:“蓝色”},
{速度:80,颜色:“黄色”},
{速度:79,名称:“橙色”}
];
功能GetFastTestCar(汽车){
var fastestCar={};
if(车辆长度){
cars.forEach(car=>{
fastestCar=fastestCar.speed>car.speed?fastestCar:car;
});
}
返回速度最快的车;
}

控制台日志(getFastestCar(cars))这可能只是个人喜好,但我不喜欢在涉及比较的任务中使用Array.reduce。我认为以下几点更容易理解:

const cars=[
{速度:20,颜色:“红色”},
{速度:5,颜色:“蓝色”},
{速度:80,颜色:“黄色”},
{速度:79,名称:“橙色”}
];
功能GetFastTestCar(汽车){
var fastestCar={};
if(车辆长度){
cars.forEach(car=>{
fastestCar=fastestCar.speed>car.speed?fastestCar:car;
});
}
返回速度最快的车;
}

控制台日志(getFastestCar(cars))
我认为您只是缺少函数中的
返回
。您可以这样实现
const max=uu.maxBy(cars,car=>car.speed)。我为您创建了一个。我认为您只是缺少了函数中的
返回
。作为补充,您可能会觉得使用这样的库更舒服。您可以这样实现
const max=uu.maxBy(cars,car=>car.speed)。我为你创造了一个新的世界。
function getFastestCar(cars) {
   cars.reduce(function (prevFastestCar,curFastestcar) {
       if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
       else return prevFastestCar;
   }, {speed: -Infinity, name: "test"});
};