LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】new Array()に関するメモ

Posted at

イディオムで覚えていたこと

「指定した要素数の空配列を作り、mapで回して連番を得る」というのをnew Arrayを用いて実現するやり方。

const three = new Array(3).fill();
// three --> [undefined, undefined, undefined]

// 配列の要素自体には用がなく、インデックスで連番を得る
const comics = three.map((el, idx) => { return `『ドラえもん』第${idx + 1}巻`} );
// comics --> ["『ドラえもん』第1巻", "『ドラえもん』第2巻", "『ドラえもん』第3巻"]

ふと疑問: fill()ってなんで要るんだっけ?

試してみた

const three2 = new Array(3);
// three --> [<3 empty items>]
console.log(three2);
// undefined
console.log(three2.length)
// 3
const comics2 = three2.map((el, idx) => { return `『ジョジョの奇妙な冒険』第${idx + 1}巻`} );
// three2 --> [<3 empty items>]

わかったこと

new Array()に渡した値は単にlengthを定義するだけで、要素はundefinedではなく空のスロットになる。

JS公式レファレンスより(強調は筆者)

Array コンストラクターに渡された唯一の引数が 0 から 232-1 の間 (両端を含む) の整数であった場合は、新しい JavaScript の配列を返し、その length プロパティがその値になります (注: これは arrayLength 個の空のスロットを持つ配列であり、実際に undefined の値が入ったスロットではありません)。

わからんこと

空のスロットってなんだよ…

参考記事

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