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

JavaScript项目:RestCountries API的forEach循环前置代码求助

解决RestCountries API遍历结果并渲染国家信息的问题

核心问题拆解

你当前代码的主要问题是异步逻辑顺序错误:fetch是异步操作,API返回的data要在then回调里才能拿到,你把forEach写在then外面,这时候数据还没返回,自然无法遍历。另外,RestCountries v3.1的返回数据结构和你代码里写的属性不匹配,直接用会导致渲染失败,这部分也要同步修正。

修正后的完整JavaScript代码

const countries = document.querySelector('.countries')
const btn = document.getElementById('btn')

function getCountries(){
    const search = document.querySelector('.search').value
    // 每次搜索前清空旧结果,避免重复渲染
    countries.innerHTML = ''
    
    fetch(`https://restcountries.com/v3.1/lang/${search}`)
    .then((response) => {
        // 处理请求失败的情况
        if (!response.ok) throw new Error('未找到对应语言的国家或请求失败')
        return response.json()
    })
    .then((data) => {
        // 拿到API返回的数组后,直接遍历调用showCountry
        data.forEach(countryItem => {
            showCountry(countryItem)
        })
    })
    .catch(err => {
        // 显示错误提示
        countries.innerHTML = `<p style="color:red; text-align:center; margin-top:20px;">${err.message}</p>`
    })
}
    
function showCountry(data){
    const country = document.createElement('div')
    country.classList.add('country')
    // 处理可能为空的字段,避免页面报错
    const capital = data.capital ? data.capital[0] : '无'
    const subregion = data.subregion || '无'
    // 提取语言名称(API返回的languages是键值对格式)
    const languages = Object.values(data.languages).join(', ')
    
    country.innerHTML = `
    <div class="country-img">
        <img src="${data.flags.svg}" alt="${data.name.common}国旗">
    </div>
    <div class="country-details">
        <h5 class="countryName">${data.name.common}</h5>
        <p><strong>Population:</strong> ${(data.population / 1000000).toFixed(2)}M</p>
        <p><strong>SubRegion:</strong> ${subregion}</p>
        <p><strong>Capital:</strong> ${capital}</p>
        <p class="languageName"><strong>Language:</strong> ${languages}</p>
    </div>`

    countries.appendChild(country)
}

关键修改说明

  1. 异步逻辑修正:把forEach直接放到fetch的第二个then回调内,确保只有拿到API返回的数组后才执行遍历渲染。
  2. 数据结构适配:
    • 国旗地址改为data.flags.svg(v3.1中国旗是包含svg/png地址的对象)
    • 国家名称改为data.name.common(返回的name对象包含通用名、官方名等字段)
    • 语言字段通过Object.values(data.languages)提取(API返回的languages是类似{eng: "English"}的键值对)
    • 首都data.capital是数组,取第一个元素或显示“无”
  3. 体验优化:每次搜索前清空旧结果,添加错误捕获逻辑,避免请求失败时页面无反馈。
  4. 简化配置:GET请求是fetch的默认方法,可省略method: "GET"配置。

原HTML代码(无需修改)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <title>Countries</title>
</head>
<body>
    <div class="container">
        <h1>Search country by language!</h1>
    </div>
    <div class="container">
        <div class="controls">
            <i class="bx bx-search"></i>
            <input type="text" placeholder="search by language.." id="search" class="search">
        </div>
        <button id="btn" onclick="getCountries()">Search Country</button>
    </div>
    <div class="countries">
        
    </div>
    <script src="script.js"></script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:30:25