Sparse Array Holes Skip Iteration

Sparse array holes are skipped by forEach and preserved by map, read as undefined by spread and includes, and created by delete without shrinking length.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
const sparse = new Array(3); // sparse array:三个位置全是 hole
sparse[1] = "filled";

// forEach 跳过 hole,回调只对真实存在的属性调用
const visited = [];
sparse.forEach((value, index) => visited.push(`${index}:${value}`));
console.log(`forEach visited: ${visited.join(" ")}`);

// map 保留 hole 的形状:结果仍是稀疏数组
const mapped = sparse.map((value) => `v=${value}`);
console.log(`map: length ${mapped.length}, 0 in mapped: ${0 in mapped}`);

// 展开会把 hole 读成 undefined:形状变密
const densified = [...sparse];
console.log(`spread: length ${densified.length}, [0] undefined: ${densified[0] === undefined}`);

// includes 把 hole 当 undefined;indexOf 不认 hole
console.log(`includes(undefined): ${sparse.includes(undefined)}`);
console.log(`indexOf(undefined): ${sparse.indexOf(undefined)}`);

// delete 制造 hole 而不是缩短数组:length 不变,属性消失
const letters = ["a", "b", "c"];
delete letters[0];
console.log(`after delete: length ${letters.length}, 0 in letters: ${0 in letters}`);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

forEach visited: 1:filled
map: length 3, 0 in mapped: false
spread: length 3, [0] undefined: true
includes(undefined): true
indexOf(undefined): -1
after delete: length 3, 0 in letters: false

Inside the snippet

The file’s state is a handful of top-level bindings: sparse, visited, mapped, densified.

Points of care

  • Nothing to install: the snippet stays inside the standard library.

Putting it to use

The file announces its steps in the output: forEach visited: $, map: length $, includes(undefined): $.

Core lines

sparse.forEach((value, index) => visited.push(`${index}:${value}`));
const mapped = sparse.map((value) => `v=${value}`);

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `sparse`, `visited`, `mapped`.