簡體   English   中英

具有underscore.js和reduce的數組內的對象的和值

[英]Sum values of objects which are inside an array with underscore.js and reduce

我試圖用underscore.js及其reduce方法對內部和數組中的對象值求和。 但看起來我做錯了什么。 哪里是我的問題?

let list = [{ title: 'one', time: 75 },
        { title: 'two', time: 200 },
        { title: 'three', time: 500 }]

let sum = _.reduce(list, (f, s) => {
    console.log(f.time); // this logs 75
    f.time + s.time
})

console.log(sum); // Cannot read property 'time' of undefined

使用native reduce list已經是一個數組。

reduce回調應返回一些東西,並具有初始值。

嘗試這個:

 let list = [{ title: 'one', time: 75 }, { title: 'two', time: 200 }, { title: 'three', time: 500 }]; let sum = list.reduce((s, f) => { return s + f.time; // return the sum of the accumulator and the current time, as the the new accumulator }, 0); // initial value of 0 console.log(sum); 

注意:如果我們省略塊並使用箭頭函數的隱式返回,那么reduce調用可以更加縮短:

let sum = list.reduce((s, f) => s + f.time, 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM