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?

join("\n") で改行出力!もう console.log() 連打しない

Posted at

今日も基礎問題演習!普通にconsole.log() を10回書いても解けるけど、そんなの面倒すぎる!
配列+ join("\n") を使えば、スッキリ1行で解決できるぞ!


問題概要

以下の10 個の整数を改行区切りで出力

813, 1, 2, 923874, 23648, 782356, 3256, 2342, 24324, 112


❌ NG例: console.log() 連打

console.log(813);
console.log(1);
console.log(2);
console.log(923874);
// 以下、延々と続く…

👎 問題点:

  • 10個ならまだしも、100個あったら… 修行か?
  • 追加・修正が めんどくさすぎる
  • for ループ で回すのも書くのがダルい


✅ OK例: join("\n") で一発

const numbers = [813, 1, 2, 923874, 23648, 782356, 3256, 2342, 24324, 112];
console.log(numbers.join("\n"));

👍 改善点

  • たった2行 でスッキリ
  • 配列に追加・削除するだけでOK
  • 100個でも1000個でも楽勝!


🔍 join("\n") の役割

join("\n") を使うと、配列の各要素を改行で連結できる!

const fruits = ["apple", "banana", "grape"];
console.log(fruits.join("\n"));

🔽 出力

apple
banana
grape


🌟 これもできる

["H", "e", "l", "l", "o"].join("");  // "Hello"
["A", "B", "C"].join(", ");  // "A, B, C"


⚡ join() の良いところ!

✅ 配列の要素を1つの文字列に変換できる
✅ 区切り文字を自由に設定できる(, や – や \n など)
✅ 改行にも使える(join(“\n”))
✅ コードの可読性とメンテナンス性が向上する


⚡ 結論

改行して出力するなら join("\n") を使う!

📌 僕の失敗談と解決話!

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