如何重写myFunction使其工作



如何获得:

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))

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

此外,当price > max为false时,您不会返回任何内容,因此累加器将设置为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))

如果price不大于,则需要一个小的起始值并在函数中返回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));

最新更新