← 中文资源

简体中文版本

Array.entries 同时遍历索引与值

Array.prototype.entries 在 for-of 里同时给出索引与值;keys/values 各取一半,稀疏数组的洞会以 undefined 原样出现在结果中。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

0: build
1: test
2: deploy
0,1,2
true
[ 0, 'build' ]
false
[[0,"a"],[1,null],[2,"c"]]

实现说明

在这里做循环的是 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()]));