我有一个本地保存的JSON文件,其中有一堆对象/字符串。我在处理每个值时遇到了麻烦。开头看起来是这样的:
{
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
},
...在将它包含在我的JS中之后,我尝试通过控制台记录console.log(heroes.result[0].heroes[0].name)。
我知道这是个愚蠢的问题,但我想不通,now.This是我的标记:
const endpoint = './heroes.json'
let heroes = []
fetch(endpoint)
.then(blob => blob.json())
.then(data => heroes.push(data))
console.log(heroes)发布于 2018-02-27 02:32:48
结果是一个对象,而不是一个数组。您需要从中删除索引
heroes.result.heroes[0].name
var heroes={
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
}]
}
}
console.log(heroes.result.heroes[0].name)
发布于 2018-02-27 02:33:01
您需要为对象属性使用.,因为result是您需要使用的对象。代替[]
var heroes={
"result":{
"heroes":[
{
"name":"npc_dota_hero_antimage",
"id":1,
"localized_name":"Anti-Mage"
},
{
"name":"npc_dota_hero_axe",
"id":2,
"localized_name":"Axe"
}]
}
}
console.log(heroes.result.heroes[0].name)
发布于 2018-02-27 04:09:23
`heroes.result.heroes[0].name` 这应该可以了。记住,result是第一个对象“heroes”的属性,第二个“heroes”是对象“result”的属性。
然而,第二个“英雄”的关键是一个数组。因此,您使用索引来访问数组中的第一个元素:heroes[0]。
第三,heroes[0]包含一个对象,所以我们要访问它的属性'name',因此是.name。
https://stackoverflow.com/questions/48994839
复制相似问题