You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript/React Native的for of循环中如何同时获取元素值与索引?

如何在for...of循环中同时获取索引和元素?

嘿,我太懂你这种“明明记得有个简洁写法但翻遍资料都找不到”的感觉了!你回忆里的array.indexed()其实并不是JavaScript原生提供的方法——大概率是某个第三方库(比如lodash或者一些自定义工具库)扩展的数组方法,或者是你之前见过的某个项目里自己封装的工具函数。

不过别担心,JavaScript原生就有完美替代方案,用Array.prototype.entries()就行!它会返回一个迭代器,每次迭代都会给出一个包含索引和元素值的数组,刚好能匹配你想要的解构写法:

const fruits = ['apple', 'banana', 'cherry'];

for (const [index, element] of fruits.entries()) {
  console.log(`索引${index}:${element}`);
}
// 输出:
// 索引0:apple
// 索引1:banana
// 索引2:cherry

至于你印象里的array.indexed(),如果确实想实现类似的效果,也可以自己写个简单的工具函数(不推荐随意修改原生数组原型,避免污染全局环境):

// 自定义工具函数
const indexed = (array) => array.entries();

// 使用方式和你记忆中的几乎一致
for (const [index, element] of indexed(fruits)) {
  console.log(`索引${index}:${element}`);
}

当然,如果你不想用entries(),常见的带索引循环替代方案还有这些:

  • 用Array.prototype.forEach(),天生支持索引参数,写法简洁:
fruits.forEach((element, index) => {
  console.log(`索引${index}:${element}`);
});
  • 传统的for循环,兼容性拉满,适合需要中断循环的场景:
for (let index = 0; index < fruits.length; index++) {
  const element = fruits[index];
  console.log(`索引${index}:${element}`);
}

内容的提问来源于stack exchange,提问作者Chen Li Yong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:07:51