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?

More than 1 year has passed since last update.

配列のループは、基本のfor of loopでも、for loopでも書ける!

Last updated at Posted at 2022-08-24

JAVASCRIPTのforループを整理するための記事です。

この記事を見るとわかること:
配列のループfor of loopでかける配列のループは、for loop でもかけるよ

<書きたいもの>
仮引数:数値型の要素を持つ配列
返り値;与えられた配列のすべての数字の合計

actual = sumArray([1, 2, 3, 4]);
expected = 10;

その1 for of loop を使う
(配列の各要素にアクセスする)

function sumArray(numbers) {

let result = 0
for (const number of numbers){
   
    result = number + result
   
}
return result;

}

その2 for loop を使う
(配列の要素、オブジェクトのキー、一つ一つに同じ処理を繰り返したいとき)

function sumArray(numbers) {

  let result = 0
for (let i = 0; i < numbers.length; i ++){

result = numbers[i]  + result;

}
return result;

}

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?