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

slice(1) × forEach() でスマートに配列処理!

Last updated at Posted at 2025-02-25

高2の僕が「配列の要素を出力するだけでしょ?」と油断したら、思わぬ落とし穴が…。
for 文でループしたら、余計な値まで出力されてしまった!
解決策は slice(1) × forEach() のコンボ。これがシンプルで強い!

NG例(失敗コード)

rl.on('close',() => {
    for (let i = 0; i < lines.length; i++) {
        console.log(lines[i]);  // n(最初の要素)まで出力されてしまう!
    }
});

OK例(改善コード)

rl.on('close',() => {
    lines.slice(1).forEach(num => {
        console.log(num);
    });
});

ポイント
✅ slice(1) で最初の要素(n)を除外
✅ forEach() でシンプルにループ処理

学んだこと
💡 slice(1) は、2つ目の要素から最後までの新しい配列を返す
💡 forEach() は、配列の要素ごとに処理を実行するのに便利
💡 意図しない出力を防ぐには、データ構造をしっかり理解することが大事!

僕の失敗談と解決話→ Paizaで基本マスター

0
0
2

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