减少 returns 未定义
Reduce returns undefined
我有一组对象(汽车):
var car = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
和一个函数,应该 return 数组中最快的汽车:
function getFastestCar(cars) {
cars.reduce(function (prevFastestCar,curFastestcar) {
if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
else return prevFastestCar;
}, {speed: -Infinity, name: "test"});
};
搜索了几个小时后,我找不到任何解决函数 return 未定义的方法。我调试了代码,函数工作得很好,除了最后一个 "step" 它以某种方式用未定义替换了最快的汽车。我试图理解 reduce 方法背后的概念我知道有更简单的方法可以做到这一点,但我很好奇为什么它不能正常工作。
您需要return
函数的减少值。
return cars.reduce(..);
参见 reduce 的描述。
Return value
The value that results from the reduction.
这可能只是个人喜好,但我不喜欢将 Array.reduce 用于涉及比较的任务。我认为以下内容更容易理解:
const cars = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
function getFastestCar(cars) {
var fastestCar = {};
if (cars.length) {
cars.forEach(car => {
fastestCar = fastestCar.speed > car.speed ? fastestCar : car;
});
}
return fastestCar;
}
console.log(getFastestCar(cars));
我有一组对象(汽车):
var car = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
和一个函数,应该 return 数组中最快的汽车:
function getFastestCar(cars) {
cars.reduce(function (prevFastestCar,curFastestcar) {
if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar;
else return prevFastestCar;
}, {speed: -Infinity, name: "test"});
};
搜索了几个小时后,我找不到任何解决函数 return 未定义的方法。我调试了代码,函数工作得很好,除了最后一个 "step" 它以某种方式用未定义替换了最快的汽车。我试图理解 reduce 方法背后的概念我知道有更简单的方法可以做到这一点,但我很好奇为什么它不能正常工作。
您需要return
函数的减少值。
return cars.reduce(..);
参见 reduce 的描述。
Return value
The value that results from the reduction.
这可能只是个人喜好,但我不喜欢将 Array.reduce 用于涉及比较的任务。我认为以下内容更容易理解:
const cars = [
{speed: 20, color: "red"},
{speed: 5, color: "blue"},
{speed: 80, color: "yellow"},
{speed: 79, name: "orange"}
];
function getFastestCar(cars) {
var fastestCar = {};
if (cars.length) {
cars.forEach(car => {
fastestCar = fastestCar.speed > car.speed ? fastestCar : car;
});
}
return fastestCar;
}
console.log(getFastestCar(cars));