You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch()请求接口可打印完整对象但访问属性返回undefined怎么办

问题原因

你调用的https://restcountries.com/v3/alpha/接口返回值为数组结构,而非你以为的国家信息对象。你打印完整json时看到的包含borders属性的对象,实际是数组的第一个元素。数组本身不存在borders属性,所以直接访问json.borders会得到undefined。

解决方法

取返回数组的第一个元素,再访问对应属性即可,修改后代码如下:

const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`);
let json = await response.json();
console.log("this is my json file: ", json[0].borders)

如果需要兼容异常场景避免报错,可以加层非空判断:

const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`);
let json = await response.json();
if (json?.length) {
  const countryInfo = json[0];
  console.log("borders: ", countryInfo.borders);
  // 其他属性均从countryInfo读取即可,例如countryInfo.capital、countryInfo.name等
}

内容的提问来源于stack exchange,提问作者Kubaguette The Testobun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:48:03