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?

split(" ") の初心者らしいミスと正しい使い方

Posted at

今日は改行出力の問題を解いた!「配列を split(" ") で分割すればいいっしょ?」って思った僕、無事撃沈しました。
実は split() は文字列専用 なので、配列に使うとエラーになります。

NG例

const numbers = lines.split(" "); 
// ❌ エラー!(linesは配列)

OK例

const numbers = lines[1].split(" "); // 2行目の文字列を分割
numbers.forEach(num => console.log(num)); // 各要素を改行出力

☆ポイント
lines[1] を指定して 文字列 を取得
それに対して split(" ") を適用

💡 まとめ
split(" ") は 文字列にしか使えない(配列に使うと死ぬ)
改行出力は forEach() か join("\n") でOK

僕の失敗談と解決話!

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