如何通过Javascript从Restcountries API动态获取货币名称并渲染到HTML
实现方法
你可以通过Object.values()直接提取currencies对象的所有属性值,不需要硬编码货币代码:
- 首先在
renderCountry函数内拼接HTML模板前,先处理货币数据,同时加兜底逻辑避免接口无返回时报错:
// 提取所有货币数据,空兜底避免接口返回异常时崩溃 const currencyList = Object.values(data.currencies || {}); // 拼接货币名称,多货币用顿号分隔,无数据时显示兜底文本 const currencyText = currencyList.length ? currencyList.map(item => item.name).join('、') : '暂无货币数据'; // 如果需要同时显示货币符号,可替换为下面的写法 // const currencyText = currencyList.length // ? currencyList.map(item => `${item.name}(${item.symbol})`).join('、') // : '暂无货币数据';
- 将HTML模板中原
${data.fifa}的位置替换为${currencyText}即可。
修改后的完整renderCountry代码示例:
const renderCountry = function(data, className = '') { // 新增货币数据处理逻辑 const currencyList = Object.values(data.currencies || {}); const currencyText = currencyList.length ? currencyList.map(item => item.name).join('、') : '暂无货币数据'; const html = ` <article class="country ${className}"> <img class="country__img" src="${data.flags.svg}" /> <div class="country__data"> <h3 class="country__name">${data.name.common}</h3> <h4 class="country__region">${data.region}</h4> <p class="country__row">${(+data.population / 1000000).toFixed(1)} people</p> <p class="country__row">${currencyText}</p> </div> </article> ` countriesContainer.insertAdjacentHTML ('beforeend', html); countriesContainer.style.opacity = 1; }
原理说明
Object.values()会将对象的所有可枚举属性的值转换为数组,不管货币代码是CZK、SEK还是其他值,都会被统一放入数组中。对于少数有多个法定货币的国家,用join('、')拼接也可以正常显示所有货币名称,不会出现适配问题。
内容的提问来源于stack exchange,提问作者CzechCoder
相关产品推荐
相关产品推荐

