类型错误:无法读取 js 中未定义的属性(读取"名称")


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'))

这是通过promise 获取数据的代码

货币:NGN:{名称:"尼日利亚奈拉",符号:"₦"}这是数组示例数组,我正在尝试获取"name"我认为数据.货币[0].名称应该起作用,而不是

如果我以这种方式运行代码,

<p class="country__row">< <span>💰>/span>${data.currencies[0]}</p>

在没有实际数据的情况下,我得到了未定义的结果,显示哪一个是真正的问题

如果我以这种方式运行,

<p class="country__row"><span>< 💰</span>${data.currencies[0].name}</p>

我得到这个错误<TypeError:无法读取未定义(读取"name"(和i>的属性;不知道为什么

<这里的主要问题是,当我试图读取和输出数据并只运行数据时,我没有添加.name。currencies[0],它给了我未定义的信息,当我尝试运行数据时。currencys[0]。name给了我类型错误,我认为这不应该是因为我认为我读取数据正确。

在返回的数据中,currencies不是数组。。。但是一个物体。所以您不能使用currencies[0]。您需要知道物业名称。

现在。。。你可以"知道";它使用Object.keys创建一个数组,其中包含在对象中找到的键
然后使用第一个数组项作为对象的键。

因此Object.keys(data.currencies)[0]将为您提供货币对象中的第一个键。

const countries = ["nigeria", "brazil", "canada", "france", "italy"]
countries.forEach((country) =>
fetch(`https://restcountries.com/v3.1/name/${country}`)
.then(response => {
return response.json();
})
.then(data => {
const coutryData = data[0]
const countryCurrencies = coutryData.currencies
console.log(`${country}: ${countryCurrencies[Object.keys(countryCurrencies)[0]].name}`)
})
)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

最新更新