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?

More than 3 years have passed since last update.

ワンライナーの配列の作り方

0
Last updated at Posted at 2022-12-22

概要

筆者は、JavaScriptでワンライナーの配列を作りたいなーと思うことがあります。
そんな時に、よくやる間違いをしてあれ?となることがあるので備忘録として残しておきます。

サンプル1

スプレッド構文を使ってArrayempty要素に対してundefindeを埋める方法

[...Array(3)].map((_,index)=>index))
//expected [0, 1, 2]

サンプル2

Array.prototype.fillなどを(keys())使ってemptyに対してundefindeなど埋め直してあげる方法

Array(3).fill().map((_,index)=>index))
//expected [0, 1, 2]

よくやる間違い

Array(3)で作ったempty要素に対してArray.prototype.mapをするとempty要素は無視されるので各種要素に対して処理をすることができない。

Array(3).map((_,index)=>index))
//expected [empty, empty, empty]

終わりに

実は、よくある間違いで挙げた書き方をReactのコンポーネントに対して行ってしまい何も描画されない状況に陥った。

const OneLinerList: FC<Props> = () => {
  return (
    <>
      {[...Array(2)].map((_, index) => {
        return <li key={index}>リスト {index}</li>
      })}
    </>
  )
}
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?