๐Ÿ„sparse array

JS โŸฉ object โŸฉ built-in โŸฉ Array โŸฉ sparse array

  • array that has "holes" in it.

  • "holes" are (usually) treated as undefined.

loops and array methods treat "holes" in sparse arrays differently.

  • for-of๏ผštreats "holes" as undefined.

  • forEach๏ผšignores "holes".

  • map ๏ผšpreserves holes.

  • filter ๏ผšignores holes.

๐Ÿ‘‰ how array methods deal with "holes" ?

deleting an array element leaves a โ€œholeโ€ in the array and does not change the arrayโ€™s lengthโ— (sparse array)

Array(n) vs. Array(n).fill()

Array(3)

  • ๅชๆœƒ่จญๅฎš้™ฃๅˆ—้•ทๅบฆ {length: 3}๏ผŒไธฆไธๆœƒ่จญๅฎšใ€Œๆ•ดๆ•ธ็ดขๅผ•ใ€ๅฑฌๆ€ง

  • ๅฆ‚ๆžœๅš .map()๏ผŒๅชๆœƒๅพ—ๅˆฐ็ฉบ้™ฃๅˆ—๏ผŒๅ› ็‚บ .map() ๆœƒไฟ็•™ใ€Œๆดžใ€ใ€‚

Array(3).fill()

  • ๆœƒๅกซๅ…ฅ undefined๏ผŒไธฆ่จญๅฎšใ€Œๆ•ดๆ•ธ็ดขๅผ•ใ€ๅฑฌๆ€ง๏ผŒ้€™ๆ™‚ไฝฟ็”จ .map() ๅฐฑๆœƒๆœ‰ๅฏฆ้š›ๆ•ˆๆžœใ€‚

Last updated