Array entries And keys Index Iteration
Iterate arrays as [index, value] pairs with entries(), take keys() or values() alone, and stop early because the trio returns real iterators.
Code
const log = ['boot', 'connect', 'ready'];
// entries() 产出 [索引, 值] 对:for...of 直接解构,省掉手写计数器
for (const [index, entry] of log.entries()) {
console.log(index, entry);
}
// keys()/values() 单取一边;三者都是真正的迭代器,可逐步推进
const keys = log.keys();
console.log('first key:', keys.next().value);
// 迭代器可提前退出:break 只属于 for...of,forEach 无法中断
const seen = [];
for (const [index, entry] of log.entries()) {
if (index === 2) break;
seen.push(entry);
}
console.log('stopped early at:', seen.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
0 boot
1 connect
2 ready
first key: 0
stopped early at: boot,connectInside the snippet
The file’s state is a handful of top-level bindings: log, keys, seen.
What to watch for
- The guard
index === 2short-circuits the flow with an earlybreakwhen its condition holds.
Using it
The demo output is labeled (first key:, stopped early at:), so every printed line maps back to its originating operation.
Key statements
const log = ['boot', 'connect', 'ready'];
const keys = log.keys();
if (index === 2) break;
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `log`, `keys`, `seen`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.