我的任务是编写程序以找到最便宜的路线。唯一的问题是,汽车有一个油箱,需要加油。因此,我想到了这个想法,编写了一个递归函数来模拟加油过程并比较最终价格。代码看起来像这样:
calcCheapest() {
const routeBuilder = (curRoute, curPrice, curLiter) => {
let curStation = curRoute[curRoute.length - 1];
let newReachables = this.route[curStation].reachables;
if (!newReachables.length) {
if (curPrice < cheapestPrice) {
return { curRoute: curRoute, curPrice: curPrice };
} else {
return { curRoute: [], curPrice: Infinity};
}
}
else return newReachables.map(reachable => {
// multiple comparisons on how to refule
return routeBuilder([...curRoute, reachable], newPrice, newLiters)
})
}
var cheapestPrice = Infinity;
var a = routeBuilder([this.start], 0, this.curLiter);
console.log(a);
}
但是我得到的“ a”变量是:
(6)[
0: (6)[
0: (6)[
0: (6)[
0: (5)[
......
[
curPrice: 271271.03, curRoute: Array(11)[0, 194, 1305, … ]
]
…]
…]
…]
…]
…]
而且我不知道如何只返回值。如果我拿走地图前面的返回值,则我得到的“ a”是不确定的。