如何预警第一辆车将达到目标?

时间:2019-01-04 18:00:32

标签: javascript

如果(car1> maxWidth || car2> maxWidth || car3> maxWidth || car4> maxWidth || car5> maxWidth)

alert(car1> car2?'Winner car1':'Winner car2');

1 个答案:

答案 0 :(得分:0)

不仅要弄清楚哪个分数获胜,而且要弄清楚该分数属于谁。有两个数据,汽车名称和得分。

一种好的函数式编程方法是将这些汽车排列成阵列,然后使用阵列函数计算获胜者,在这种情况下为array.reduce。

// you have this part somewhere already
var car1 = 10, car2 = 20, car3 = 15, car4 = 33, car5 = 2;
var maxWidth = 12; // gotta be more than this wide to win

// make an array
var cars = [car1, car2, car3, car4, car5];

// reduce the array to find the winner
var winner = cars.reduce((leader, curr, i) => {
  if (curr > leader.width)
    return {width: curr, name: "car" + (i + 1)};
  
  return leader;
}, {width: maxWidth, name: "nobody"}); // set "nobody" as the initial leader

console.log(winner.name + " wins!");