遍历Fetch API响应为何返回undefined结果?
问题原因
你这里的核心问题是误用了for...in遍历数组:for...in迭代的是数组的索引(字符串形式,比如"0"、"1"),而非数组中的每一个post对象。所以post.title本质是在访问字符串的title属性,自然返回undefined。
修复方案
可以用以下几种方式替换原来的遍历逻辑:
方式1:使用for...of遍历数组(推荐)
for...of会直接迭代数组中的每个元素,也就是每个post对象:
window.onload = function() { fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then(json => { console.log(json); for (const post of json) { console.log(post.title); var div = document.createElement('div'); var title = document.createElement('h1'); var body = document.createElement('p'); title.innerText = post.title; body.innerText = post.body; div.appendChild(title); div.appendChild(body); document.body.appendChild(div); } }) }
方式2:使用数组的forEach方法
这是遍历数组的常用方法,逻辑更直观:
window.onload = function() { fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then(json => { console.log(json); json.forEach(post => { console.log(post.title); var div = document.createElement('div'); var title = document.createElement('h1'); var body = document.createElement('p'); title.innerText = post.title; body.innerText = post.body; div.appendChild(title); div.appendChild(body); document.body.appendChild(div); }); }) }
方式3:普通for循环(传统写法)
如果习惯传统循环,也可以通过索引直接获取数组元素:
window.onload = function() { fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then(json => { console.log(json); for (let i = 0; i < json.length; i++) { const post = json[i]; console.log(post.title); var div = document.createElement('div'); var title = document.createElement('h1'); var body = document.createElement('p'); title.innerText = post.title; body.innerText = post.body; div.appendChild(title); div.appendChild(body); document.body.appendChild(div); } }) }
补充说明
for...in的设计初衷是遍历对象的可枚举属性,虽然能遍历数组,但会把数组原型链上的自定义属性/方法也遍历出来,因此不适合用来遍历数组元素。遍历数组优先选择for...of、forEach或普通for循环。
内容的提问来源于stack exchange,提问作者ahyes
相关产品推荐
相关产品推荐

