如何遍历对象类型的关联数组?附gridRegions示例代码
遍历JavaScript对象类型关联数组的几种方法
针对你手里的gridRegions这种键值对结构的对象,在JavaScript里有不少实用的遍历方式,我给你列几个最常用的:
1. 传统for...in循环(兼容旧环境)
这是最经典的遍历对象键的方式,记得加上hasOwnProperty检查,避免遍历到原型链上的继承属性:
for (const regionKey in gridRegions) { // 确保只处理对象自身的属性 if (gridRegions.hasOwnProperty(regionKey)) { const region = gridRegions[regionKey]; // 这里可以做你需要的操作,比如打印信息或处理gridLabels console.log(`区域标识:${region.label},包含网格数:${region.numGrids}`); } }
2. Object.keys() + 数组遍历(简洁易读)
Object.keys()会返回对象自身所有可枚举属性的键组成的数组,搭配forEach遍历很清爽:
Object.keys(gridRegions).forEach(regionKey => { const region = gridRegions[regionKey]; console.log(`区域键名:${regionKey},纬度范围:${region.lats[0]} 到 ${region.lats[1]}`); });
3. Object.entries() + for...of(ES6+ 推荐)
如果你的运行环境支持ES6及以上,Object.entries()是最方便的——它直接返回[键, 值]形式的数组,用for...of遍历可以同时拿到键和值:
for (const [regionKey, region] of Object.entries(gridRegions)) { console.log(`区域:${region.label},经度范围:${region.lons[0]} 到 ${region.lons[1]}`); // 比如在这里给gridLabels填充数据 // region.gridLabels = someFunctionToGenerateLabels(); }
小提示
- 如果需要兼容IE这类旧浏览器,优先选
for...in的写法; - 要是用的现代项目(比如React/Vue项目),
Object.entries()+for...of的组合代码更简洁,可读性也更高。
内容的提问来源于stack exchange,提问作者cpeddie
相关产品推荐
相关产品推荐

