我如何重写 myFunction 使其工作

how do I rewrite the myFunction so it works

我如何得到这个:

console.log(items.reduce(myFunction))

产生与以下相同的答案:

console.log(items.reduce((max, {price}) => price > max ? price : max, 0))

let items = [
    {
      itemName: "Effective Programming Habits",
      type: "book",
      price: 13.99
    },
    {
      itemName: "Creation 3005",
      type: "computer",
      price: 299.99
    },
    {
      itemName: "Finding Your Center",
      type: "book",
      price: 15.00
    }
  ]
  
  

console.log(items.reduce((max, {price}) => price > max ? price : max, 0))



function myFunction(max, {price}){

if(price > max ){

 
return price
 
}

}

console.log(items.reduce(myFunction))

如果 price 不大于 price,则函数中需要一个较小的起始值和 return max

function myFunction(max, { price }) {
  if (price > max) {
    return price;
  }
  return max;
}

let items = [{ itemName: "Effective Programming Habits", type: "book", price: 13.99 }, { itemName: "Creation 3005", type: "computer", price: 299.99 }, { itemName: "Finding Your Center", type: "book", price: 15.00 }]

console.log(items.reduce((max, { price }) => price > max ? price : max, 0))

console.log(items.reduce(myFunction, -Number.MAX_VALUE));

如果没有第二个参数传递给 reduce 数组的第一个元素将用作累加器的初始值(这在您的情况下很糟糕,因为每个元素都是一个对象);

此外,当 price > max 为假时,您不会返回任何内容,因此累加器将设置为 undefined

let items = [{
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }
]



console.log(items.reduce((max, {
  price
}) => price > max ? price : max, 0))



function myFunction(max, {
  price
}) {
  if (price > max) {
    return price
  }
  return max
}

console.log(items.reduce(myFunction, 0))