質問するログイン新規登録

回答編集履歴

1

処理にコメントを追加

2021/07/09 15:02

投稿

taku-hu
taku-hu

スコア178

answer CHANGED
@@ -1,12 +1,21 @@
1
1
  配列の値を順に処理したい時は`reduce`を使うとよいと思います。
2
- [動作デモ](https://jsfiddle.net/zq41gaxr/)
2
+ [動作デモ](https://jsfiddle.net/ms5f2pdn/)
3
3
 
4
4
  ```javascript
5
+ const array = [
6
+ { foo: 1 },
7
+ { bar: 2 },
8
+ { foo: -2 },
5
- const array = [{ foo: 1 }, { bar: 2 }, { foo: -2 }, { foo: 3, bar: 4 }];
9
+ { foo: 3, bar: 4 }
10
+ ]
6
11
 
12
+ // reduce内のコールバック関数の第1引数は現在の値、つまり一巡目はreduceの第二引数である初期値の0
13
+ // それにコールバック関数の第2引数である現在処理している値からfooを取り出して足していく
14
+ // ただしarray内のオブジェクトにはfooがundefinedの場合があるので{ foo = 0 }として無かった場合のデフォルト値を設定している
7
- const foo = array.reduce((acc, { foo = 0 }) => acc + foo, 0);
15
+ const foo = array.reduce((acc, { foo = 0 }) => acc + foo, 0)
8
- const bar = array.reduce((acc, { bar = 0 }) => acc + bar, 0);
16
+ const bar = array.reduce((acc, { bar = 0 }) => acc + bar, 0)
9
17
 
10
- console.log(foo);
18
+ console.log(foo)
11
- console.log(bar);
19
+ console.log(bar)
20
+
12
21
  ```