[英]So how can I sum all the values in all objects in an array which is coming from react redux?
這是反應 redux 減速器文件,其中數字數組是:
const initialState = {
numbers: [ { name: 'max', num: 3 }, { name: 'jack', num: 2 } ]
}
這就是我想對從反應 redux state 減速器文件收到的 numbers 數組中所有對象中的所有 num 值求和的方式
在組件中:
useEffect(() => {
const total = props.numbers.reduce((prev, current) => {
return prev + current.num, 0;
});
console.log(total);
console.log(props.numbers);
}, []);
這是來自 useEffect 的控制台日志:
0
(2) [{…}, {…}]
0: {name: "max", num: 3}
1: {name: "jack", num: 2}
length: 2
__proto__: Array(0)
總 const 只是 0 並且它不起作用。
那么如何將來自 redux 減速器文件的數組中所有對象中的所有 num 值相加?
, 0
應該是reduce
的第二個參數,而不是return
:
const total = props.numbers.reduce((prev, current) => {
return prev + current.num;
}, 0);
你需要修復減少:
const total = props.numbers.reduce((prev, current) => {
return prev + current.num;
}, 0);
您也可以使用map function
sum = 0;
props.numbers.map(n => {
sum+= n.num;
})
您需要為prev
提供一個初始值,作為reduce
的第二個參數。 如果未提供,則在第一次運行期間,回調 function 的第一個參數是數組的第一個元素,回調 function 的第二個參數是數組的第二個元素。 然后將返回值傳遞給第一個參數,下一個元素是第二個值。
因此,要添加,我添加了0
作為初始值。
const numbers = [ { name: 'max', num: 3 }, { name: 'jack', num: 2 } ] const total = numbers.reduce((prev, { num }) => { return prev + num }, 0) console.log(total)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.