实现说明
在这里做循环的是 for (const [index, stage] of stages.entries())。
顶层就这几处状态:stages、it、sparse。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件用顶层绑定保存自己的状态:stages、it、sparse。
核心语句
const stages = ['build', 'test', 'deploy'];
const it = stages.entries();
const sparse = ['a', , 'c'];
代码示例
const stages = ['build', 'test', 'deploy'];
// for-of over .entries() yields [index, value] pairs: enumeration without a
// manual counter variable to keep in sync
for (const [index, stage] of stages.entries()) {
console.log(index + ': ' + stage);
}
// .keys() yields just the indices, .values() just the elements
console.log([...stages.keys()].join(','));
console.log([...stages.values()].length === stages.length);
// entries() returns an iterator, so each pass consumes from its own cursor
const it = stages.entries();
console.log(it.next().value);
console.log(it.next().done);
// Sparse arrays still report real indices; holes come back as undefined
const sparse = ['a', , 'c'];
console.log(JSON.stringify([...sparse.entries()]));