使用hasOwnProperty检测嵌套数字键:宝可梦API二级类型判断失效
问题分析
你写的str.hasOwnProperty("types"[1])是完全错误的逻辑——"types"[1]取的是字符串"types"的第二个字符(索引从0开始),也就是'y',所以你实际在检查str对象有没有'y'这个属性,这和宝可梦的第二类型完全无关,自然永远返回false。
正确的检查方式
PokéAPI返回的types是数组,判断是否有第二类型,直接检查数组长度或者索引1是否存在即可:
写法1:检查数组长度
function CheckPropertySecondtype(str) { if (str.types.length > 1) { pokemondata.secondtype = str.types[1].type.name; console.log("Pokemon has a second type"); } else { pokemondata.secondtype = "none"; console.log("No second type"); } }
写法2:直接判断索引1是否存在
function CheckPropertySecondtype(str) { const secondTypeData = str.types[1]; if (secondTypeData) { pokemondata.secondtype = secondTypeData.type.name; console.log("Pokemon has a second type"); } else { pokemondata.secondtype = "none"; console.log("No second type"); } }
额外注意
你原来的else分支里console.log(str.types[1].type.name)会导致报错——单类型宝可梦的str.types只有1个元素,str.types[1]是undefined,访问undefined.type会抛出Cannot read properties of undefined错误,必须替换成安全的输出逻辑。
内容的提问来源于stack exchange,提问作者Ameh
相关产品推荐
相关产品推荐

