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

JS中TypeError: Cannot read properties of undefined (reading 'name')问题求助

问题

调用Rest Countries API获取国家数据渲染页面时,触发TypeError: Cannot read properties of undefined (reading 'name')错误,错误出在尝试读取data.currencies[0].name时。

相关渲染代码

const html = `
      <article class="country ${className}">
        <img class="country__img" src="${data.flags.png}" />
        <div class="country__data">
          <h3 class="country__name">${data.name.common}</h3>
          <h4 class="country__region">${data.region}</h4>
          <p class="country__row"><span>👫</span>${(
            +data.population / 1000000
          ).toFixed(1)}</p>
          <p class="country__row"><span>🗣️</span>${data.languages[0]}</p>
          <p class="country__row"><span>💰</span>${
            data.currencies[0].name
          }</p>

        </div>
      </article>
`;
console.log(data);
countriesContainer.insertAdjacentHTML('beforeend', html);
//   countriesContainer.style.opacity = 1;
};

数据请求代码

//country 1
fetch(`https://restcountries.com/v3.1/name/${country}`)
  .then(response => {
    console.log(response);
    return response.json();
  })
  .then(data => {
    renderCountry(data[0]);
    const neighbour = data[0].borders[0];

    //if theres no neighbour return immedaitely
    //thats what the ! is for
    if (!neighbour) return;

    //country 2
    return fetch(`https://restcountries.com/v3.1/alpha/${neighbour}`);
  })
  .then(response => response.json())
  .then(data => renderCountry(data[0], 'neighbour'))

已知API返回的currencies结构示例:currencies: {NGN: {name: 'Nigerian naira', symbol: '₦'}},尝试data.currencies[0]返回undefined,但不清楚问题所在。


问题原因与解决办法

核心问题:对象与数组的读取方式混淆

API返回的currencies和languages都是键值对对象,不是数组,所以不能用[0]这种数组下标方式读取。比如currencies里的NGN是键,对应的货币信息是值;languages也是类似结构,比如{eng: 'English'}。

解决步骤

  1. 处理货币名称
    要获取货币名称,需要先提取对象里的第一个值。可以用Object.values()方法把对象的所有值转成数组,再取第一个元素:

    Object.values(data.currencies)[0].name
    

    替换原代码里的data.currencies[0].name即可。

  2. 处理语言信息
    同样,data.languages[0]也会报错,因为languages是对象,需要改成:

    Object.values(data.languages)[0]
    
  3. 可选:增加容错处理
    部分国家可能没有货币或语言数据(极少数情况),可以添加判断避免报错:

    // 货币名称容错
    const currencyName = data.currencies ? Object.values(data.currencies)[0]?.name : '无';
    // 语言容错
    const language = data.languages ? Object.values(data.languages)[0] : '无';
    

    然后在模板字符串里使用${currencyName}和${language}。

修改后的渲染代码片段

const currencyName = data.currencies ? Object.values(data.currencies)[0]?.name : '无';
const language = data.languages ? Object.values(data.languages)[0] : '无';

const html = `
      <article class="country ${className}">
        <img class="country__img" src="${data.flags.png}" />
        <div class="country__data">
          <h3 class="country__name">${data.name.common}</h3>
          <h4 class="country__region">${data.region}</h4>
          <p class="country__row"><span>👫</span>${(
            +data.population / 1000000
          ).toFixed(1)}</p>
          <p class="country__row"><span>🗣️</span>${language}</p>
          <p class="country__row"><span>💰</span>${currencyName}</p>

        </div>
      </article>
`;

内容的提问来源于stack exchange,提问作者Kukoyi Tomiwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:39:22