๐sparse array
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
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 .
๏ผignores "holes".
map ๏ผpreserves holes.
filter ๏ผignores holes.
๐
an array leaves a โholeโ in the array and does not change the arrayโs lengthโ (sparse array)
Array(3)
ๅชๆ่จญๅฎ้ฃๅ้ทๅบฆ {length: 3}
๏ผไธฆไธๆ่จญๅฎใๆดๆธ็ดขๅผใๅฑฌๆง
ๅฆๆๅ .map()
๏ผๅชๆๅพๅฐ็ฉบ้ฃๅ๏ผๅ ็บ .map()
ๆไฟ็ใๆดใใ
Array(3).fill()
ๆๅกซๅ
ฅ undefined
๏ผไธฆ่จญๅฎใๆดๆธ็ดขๅผใๅฑฌๆง๏ผ้ๆไฝฟ็จ .map()
ๅฐฑๆๆๅฏฆ้ๆๆใ
if an array literal contains multiple commas in a row, with no value between, the array is sparse.
array literal syntax allows an optional trailing comma, so [,,]
has a length of 2, not 3โ
let arr = [];
arr[1] = 1;
arr[3] = 2;
// โญ๏ธ same as: [ , 1, , 2 ]
// ^ ^ <---- holes โญ๏ธ