2
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?

【JavaScript】reduceメソッドの使い方をif文と比較して学習

Posted at

はじめに

JavaScriptの学習を進めていく中で、reduceを使って合計の数値を求める課題にあたったため使い方について調べ、アウトプットを兼ねてまとめます。

reduceメソッドとは

  • 以下が基本構文
配列.reduce(function(累積値, 要素) { })
  • 第1引数に「累積値」、つまり配列要素を順番に処理していった値が格納される
  • 第2引数の「要素」が処理されている配列要素を意味する

デモコード

sample.js
let numbers = [1, 2, 3, 4, 5];

let totalNumber = numbers.reduce((a, b) => {
  return a + b;
}, 0);

console.log(totalNumber); // 15

同じ意味のコード

if文でも同じ挙動が確認できます。

sample.js
const number = [1, 2, 3, 4, 5];
let sum = 0;
for(const num of number){
  sum += num;
}
console.log(sum); // 15

reduceメソッドとfor文をくらべると

  • for文の場合の場合は、初期値(合計値)を先に宣言しておく必要がある
  • reduceメソッドを使った方が記述量が減る(今回はデモコードが簡単なためあまり変わらず)

おわりに

調べながらメソッドを使い、アウトプットすることでメソッドの使い方の理解度が深まりました。
同じく学習中の方にreduceメソッドについて少しでも参考になりましたら幸いです。

参考

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://zenn.dev/rabee/articles/reduce-total-num
https://lorem-co-ltd.com/reduce-basic/

2
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
2
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?