[英]Why am I getting Uncaught (in promise) TypeError: Cannot read property 'type' of undefined?
Here is my initial code I wrote to console log the data I want这是我为控制台记录我想要的数据而编写的初始代码
const fetchPokemon2 = () =>
{
for (let i = 1; i <= 151; i++)
{
const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
fetch(url)
.then( res => res.json())
.then( data =>
{
console.log(data);
const pokemon = {}
if (data.types['1'])
{
pokemon['name'] = data.name;
pokemon['id'] = data.id;
pokemon['sprite'] = data.sprites['front_default'];
pokemon['type1'] = data.types["0"].type.name;
pokemon['type2'] = data.types["1"].type.name;
}
else
{
pokemon['name'] = data.name;
pokemon['id'] = data.id;
pokemon['sprite'] = data.sprites['front_default'];
pokemon['type1'] = data.types["0"].type.name;
}
console.log(pokemon);
})
}
}
fetchPokemon2();
It worked fine but this isnt the recommended way so I'm trying to do this它工作正常,但这不是推荐的方式,所以我正在尝试这样做
const fetchPokemon = () =>
{
const promises = [];
for (let i = 1; i <= 151 ; i++)
{
const url = `https://pokeapi.co/api/v2/pokemon/${i}`
promises.push(fetch(url).then(resp => resp.json()));
};
Promise.all(promises).then( results =>
{
const pokemon = results.map(data =>
( { name : data.name
, id : data.id
, sprite : data.sprites["front_default"]
, type : data.types["0"].type.name
, type2 : data.types["1"].type.name
}
));
console.log(pokemon);
});
};
fetchPokemon()
However this line of code然而这行代码
type2: data.types["1"].type.name
type2:data.types["1"].type.name
is giving the error Uncaught (in promise)正在给出错误未捕获(承诺)
TypeError: Cannot read property 'type' of undefined类型错误:无法读取未定义的属性“类型”
which is confusing me a lot because this type: data.types["0"].type.name is perfectly fine could anyone help me out with this?这让我很困惑,因为这种类型:data.types["0"].type.name非常好,谁能帮我解决这个问题?
This happens when there is no value for the specified array or object index.当指定的数组或对象索引没有值时会发生这种情况。 That means
data.types[1]
is probably undefined, hence the error Cannot read property 'type' of undefined for data.types[1].type...
这意味着
data.types[1]
可能是未定义的,因此错误无法读取data.types[1].type...
的 undefined 属性 'type' data.types[1].type...
In the second code sample, you aren't checking if data.types[1]
exists.在第二个代码示例中,您没有检查
data.types[1]
存在。 You can always access the value safely by doing:您始终可以通过执行以下操作安全地访问该值:
...
type2: data.types[1] && data.types[1].type && data.types[1].type.name
...
In the API response, some of the values have only 1 element in the types array.在 API 响应中,某些值在 types 数组中只有 1 个元素。 That could be the issue.
这可能是问题所在。 You need to check if data exists or not before assigning them.
在分配数据之前,您需要检查数据是否存在。
type2: data.types[1] && data.types[1].type && data.types[1].type.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.