JavaScript fetch获取数组型API响应时无法正确读取字段值
问题原因
接口响应解析后最外层是数组结构,不是普通键值对对象,直接在数组实例上访问example属性会得到undefined,自然无法读取到目标值。
接口返回的结构参考:
[ { "example": "true" } ]
基础修复方案
数组需要先通过下标索引取出内部的对象元素,再访问对象上的example字段。如果接口固定返回仅包含一个对象的数组,直接取下标为0的元素即可,修正后的代码如下:
.then(res => res.json()) .then(json => { console.log(json[0].example) })
兼容优化写法
如果无法保证接口永远返回非空数组,可以增加校验逻辑避免运行报错:
.then(res => res.json()) .then(json => { let exampleValue = undefined; if (Array.isArray(json) && json.length > 0) { exampleValue = json[0].example; } console.log(exampleValue); })
内容的提问来源于stack exchange,提问作者Doogy
相关产品推荐
相关产品推荐

