for...of 配合 entries() 可同时获取索引和值,返回 [index, value] 数组并支持解构;entries() 适用于数组、字符串、类数组对象;keys()、values()、entries() 三者分别遍历索引、值、键值对。

在 JavaScript 中,for...of 本身不直接提供索引,但配合 Array.prototype.entries() 就能轻松拿到索引和值——它返回一个可迭代对象,每一项是 [index, value] 形式的数组,正好适合解构。
用 entries() + 解构获取索引和值
entries() 返回的是键值对迭代器,每个元素是长度为 2 的数组:[索引, 元素]。在 for...of 中用 const [i, v] of arr.entries() 即可直接解构出索引 i 和值 v:
const arr = ['a', 'b', 'c'];
for (const [i, v] of arr.entries()) {
console.log(i, v); // 0 'a' → 1 'b' → 2 'c'
}
entries() 也适用于类数组或字符串
只要对象有合法的 length 和数字索引(如 arguments、NodeList、字符串),就能用 entries():
const str = 'hi';
for (const [i, char] of str.entries()) {
console.log(i, char); // 0 'h' → 1 'i'
}
// NodeList 示例(如 document.querySelectorAll)
const buttons = document.querySelectorAll('button');
for (const [i, btn] of buttons.entries()) {
btn.dataset.index = i; // 给每个按钮加 data-index
}
注意:不要混淆 keys()、values() 和 entries()
三者都返回迭代器,但用途不同:
-
arr.keys()→ 只遍历索引:0, 1, 2... -
arr.values()→ 只遍历值:'a', 'b', 'c'...(等价于直接for...of arr) -
arr.entries()→ 遍历[index, value]对,是唯一同时拿到两者的原生方式
替代方案对比(不推荐但需了解)
虽然可以用 for...let i = 0; i 或 <code>arr.forEach((v, i) => {...}),但它们各有局限:
-
for循环写法冗长,且不能直接用break/continue控制entries()迭代器(其实可以,只是不如for...of直观) -
forEach无法中途跳出循环(return只退出当前回调) -
entries()+for...of简洁、语义清晰、支持break/continue,是现代首选
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











