[英]React JS Get Sum of Numbers in Array
我有這個數組
const data = [
{"One",prix:100},
{"Two",prix:200},
{"Three",prix:300}
]
我想得到所有這些prix
的總和,如下所示:
sum = 600
您可以使用reduce
:
data.reduce((a,v) => a = a + v.prix , 0 )
const data = [ {title: "One",prix:100}, {title: "Two",prix:200}, {title: "Three",prix:300} ] console.log((data.reduce((a,v) => a = a + v.prix, 0 )))
const sum = data.map(datum => datum.prix).reduce((a, b) => a + b)
reduce() 方法對數組的每個元素執行一個化簡器 function(您提供),從而產生單個 output 值。
arr.reduce(callback, initialValue);
reducer 將只返回一個值和一個值,因此名稱為 reduce。 回調是為數組中的每個元素運行的 function。
和 Function arguments 函數(總計,當前值,索引,arr):
Argument Description
total Required.The initialValue, or the previously returned value of the function
currentValue Required.The value of the current element
currentIndex Optional.The array index of the current element
arr Optional.The array object the current element belongs to
在這個例子中使用這個代碼:
const data = [ {title:"One",prix:100}, {title:"Two",prix:200}, {title:"Three",prix:300} ]; const result = data.reduce((total, currentValue) => total = total + currentValue.prix,0); console.log(result); // 600
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.