1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

reduceメソッドで配列の合計値を取得する(JavaScript)

Posted at

状況

  • JavaScriptで配列の合計値を取得したい
  • for文のようなループ処理は使用せずワンラインで記述したい

配列の合計値を取得する記述

const array = [1, 2, 3];

const result = array.reduce((sum, current) => sum + current, 0); 
console.log(result);

6

解説

  • 処理の流れ
    ※引数のsum, currentは自身で好きな名前を使用できる
    1. 初期値を0に設定しているので、累積値であるsumに代入される
    2. currentに配列の要素が一つずつ代入され、sumと足し算される
    3. 配列の全ての要素がsumと足し算されるとresultに代入される
      sumは累積値なので、
      0 + 1 = 1
      1 + 2 = 3
      3 + 3 = 6
      といった増え方をする
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?