如何遍历JavaScript对象优化重复的平台坐标渲染代码
优化思路
核心是遍历platforms数组中的所有元素,复用同一套渲染逻辑,不用手动写死数组下标,后续新增/删除平台配置也不需要修改渲染函数的代码。
推荐写法(forEach遍历)
const platforms = [{"x":0,"y":570,"width":1000,"height":25},{"x":350,"y":100,"width":250,"height":25},{"x":750,"y":60,"width":150,"height":25},{"x":0,"y":60,"width":150,"height":25},{"x":0,"y":390,"width":90,"height":25},{"x":100,"y":440,"width":90,"height":25},{"x":200,"y":490,"width":90,"height":25},{"x":800,"y":390,"width":90,"height":25},{"x":710,"y":440,"width":90,"height":25},{"x":620,"y":490,"width":90,"height":25},{"x":392,"y":262,"width":90,"height":25},{"x":414,"y":201,"width":90,"height":25},{"x":133,"y":210,"width":90,"height":25}] function renderplat(){ ctx.fillStyle = "#45597E"; // 遍历所有平台配置执行渲染 platforms.forEach(platform => { ctx.fillRect(platform.x, platform.y, platform.width, platform.height) }) }
兼容旧环境写法(for循环遍历)
如果需要适配不支持ES5+语法的极旧运行环境,可以用传统for循环实现:
function renderplat(){ ctx.fillStyle = "#45597E"; // 按数组长度循环遍历 for (let i = 0; i < platforms.length; i++) { const currentPlat = platforms[i] ctx.fillRect(currentPlat.x, currentPlat.y, currentPlat.width, currentPlat.height) } }
两种写法的差异
forEach写法更简洁易读,不需要手动维护索引和数组长度判断,适合绝大多数常规场景- 传统for循环在处理十万级以上元素的超大数组时性能略优,你当前的场景下元素数量极少,两种写法没有感知差异
内容的提问来源于stack exchange,提问作者Emilia Delizia
相关产品推荐
相关产品推荐

