2017-07-29 41 views
2

是否有可能將沒有迭代的對象數組的所有duration值相加?如何遍歷數組中的對象並求和一個屬性而不迭代?

const data = [ 
    { 
    duration: 10 
    any: 'other fields' 
    }, 
    { 
    duration: 20 
    any: 'other fields' 
    } 
] 

結果應該是'30'。

let result = 0 
data.forEach(d => { 
    result = result + d.duration 
}) 
console.log(result) 
+3

沒有,這是不可能進行迭代沒有迭代的陣列 - 順便說一下,我建議使用減少...'讓結果= data.reduce((R,d)= > r + d.duration,0);' –

+0

這是不可能的。一個有效的方法是使用減少https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce – Fawaz

+0

我相信量子計算機能夠解決這個問題而無需迭代。 – 2017-07-29 11:34:26

回答

0

我不工作沒有一些迭代,以獲得指定屬性的總和。

您可以使用Array#reduce的回調和起始值爲零。

const data = [{ duration: 10, any: 'other fields' }, { duration: 20, any: 'other fields' }]; 
 
let result = data.reduce((r, d) => r + d.duration, 0); 
 

 
console.log(result);

2

你不能沒有迭代做到這一點。 您可以使用array#reduce,它使用迭代。

const data = [ 
 
    { 
 
    duration: 10, 
 
    any: 'other fields' 
 
    }, 
 
    { 
 
    duration: 20, 
 
    any: 'other fields' 
 
    } 
 
]; 
 

 
var result = data.reduce(
 
    (sum, obj) => sum + obj['duration'] 
 
    ,0 
 
); 
 

 
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

相關問題