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?

【JavaScript / TypeScript】mapの結果がundefinedになる原因

Posted at

下記のような配列を作り、数値が一桁の場合は左にスペースを2つ入れて文字列として出力する処理をしたかったのですが、undefinedになってしまいました。

let array = [1, 4, 9, 16];
NG
console.log(array.map((x) => {
  let squaredString = String(x);
  
  if (squaredString.length == 1) {
    squaredString = "  " + squaredString;
  }
}));

// => (4) [undefined, undefined, undefined, undefined]

原因は条件分岐で評価されなかった値があったためでした。
mapは各要素に対して操作をして新しい配列を作るため、評価されない要素があるとダメということですね。
下記のようにして解決できました。

OK
console.log(array.map((x) => {
  let squaredString = String(x);
  
  if (squaredString.length == 1) {
    squaredString = "  " + squaredString;
  }
  return squaredString;
}));

// => (4) ['  1', '  4', '  9', '16']

参考

1
0
1

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?