使用HTML与JavaScript fetch操作列表时索引访问错误如何解决
问题原因
JavaScript 语法规范中,点运算符仅支持访问符合标识符命名规则的属性名,数字不能作为标识符开头,因此data.lands.0会被识别为尝试访问lands对象下名为字符串"0"的属性,而非读取lands数组的第0位元素。访问数组指定索引的元素需要使用方括号语法。
解决方法
1. 直接获取列表指定位置的元素
直接将数字索引放在方括号中即可,修正后的代码如下:
<script> fetch("https://queue-times.com/parks/1/queue_times.json") .then(response => { if (!response.ok) throw new Error('请求失败') return response.json() }) .then(data => { // 方括号包裹索引获取数组对应位置元素 document.querySelector("#mainKey").innerText = data.lands[0].rides[0].name }) .catch(err => console.error('数据加载出错:', err)) </script>
2. 遍历整个列表渲染所有数据
如果需要批量渲染列表内的所有元素,可以使用数组的forEach方法嵌套遍历:
首先在页面中准备用于承载列表的容器:
<ul id="rideList"></ul>
对应的JS逻辑如下:
<script> fetch("https://queue-times.com/parks/1/queue_times.json") .then(response => { if (!response.ok) throw new Error('请求失败') return response.json() }) .then(data => { const listContainer = document.querySelector("#rideList") // 遍历所有园区 data.lands.forEach(land => { // 遍历当前园区的所有游乐设施 land.rides.forEach(ride => { const li = document.createElement('li') li.innerText = `园区:${land.name} | 设施:${ride.name} | 排队时间:${ride.wait_time}分钟` listContainer.appendChild(li) }) }) }) .catch(err => console.error('数据加载出错:', err)) </script>
内容的提问来源于stack exchange,提问作者Thomas Keig
相关产品推荐
相关产品推荐

