37
19

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の関数と配列操作の基礎まとめ

Posted at

JavaScriptの関数と配列操作の基礎まとめ

配列を操作する代表的なメソッド

🔄 forEach

配列の各要素に対して順番に処理を実行します。戻り値はありません。

const fruits = ['りんご', 'バナナ', 'みかん'];

fruits.forEach(function(item) {
  console.log(item);
});

🔁 map

配列の全要素に関数を適用し、新しい配列を返します。元の配列は変わりません。

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

⚡ アロー関数

関数式を簡潔に書ける構文です。

const multiply = (x, y) => x * y;

console.log(multiply(3, 4)); // 12

const rollDice = () => Math.floor(Math.random() * 6) + 1;

console.log(rollDice());

注意
アロー関数はthisの扱いが普通の関数と違うので注意が必要です。


⏰ setTimeout

指定時間後に一度だけ処理を実行します。

setTimeout(() => {
  console.log('3秒後に表示されます');
}, 3000);

⏳ setInterval / clearInterval

一定時間ごとに繰り返し処理を実行します。停止はclearIntervalで。

const intervalId = setInterval(() => {
  console.log('2秒ごとに表示されます');
}, 2000);

setTimeout(() => {
  clearInterval(intervalId);
  console.log('繰り返しを停止しました');
}, 10000);

🔎 filter

条件を満たす要素だけを抽出した新しい配列を返します。

const ages = [10, 20, 30, 40, 50];

const adults = ages.filter(age => age >= 20);

console.log(adults); // [20, 30, 40, 50]

✅ some

1つでも条件を満たす要素があればtrueを返します。

const scores = [50, 60, 70, 80];

const hasHighScore = scores.some(score => score >= 75);

console.log(hasHighScore); // true

✅ every

すべての要素が条件を満たすかどうかを返します。

const temps = [25, 30, 28];

const allHot = temps.every(temp => temp > 20);

console.log(allHot); // true

まとめ

  • 関数は処理をまとめて再利用する強力なテクニック
  • 配列メソッドを使うと、配列の処理がシンプルでわかりやすくなる
  • アロー関数やタイマー関数も覚えておくと便利
37
19
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
37
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?