所以我一直想通过JS中的for循环访问某个元素,我正在画一个空白。我有包含15个元素的JSON对象(下面是一个示例。我试图访问“ phones” .phone_number元素,但未定义。下面也是我的for循环。
现在我只是控制台记录所有元素。返回前两个,.name和address,但是没有返回结果的电话。
for(var i=0; i < json.business.length; i++ ){
console.log(json.business[i].name);
console.log(json.business[i].found_at_address.street_line_1);
console.log(json.business[i].phones[i].phone_number);
}
{
"count_business": 15,
"business": [
{
"id": "Business.7146cd10-735f-4710-b145-93b97fe45e07",
"name": "Grace Christian Fellowship",
"industry": [
"Religious, Grantmaking, Civic, Professional, and Similar Organizations"
],
"found_at_address": {
"id": "Location.5c80fbd1-5e5a-4356-9725-5492e3942091",
"location_type": "Address",
"street_line_1": "210 2nd St",
"street_line_2": null,
"city": "Mounds",
"postal_code": "62964",
"zip4": "1144",
"state_code": "IL",
"country_code": "US",
"lat_long": {
"latitude": 37.113098,
"longitude": -89.200842,
"accuracy": "RoofTop"
},
"is_active": true,
"delivery_point": "POBoxThrowback",
"link_to_business_start_date": "2016-11-19",
"link_to_business_end_date": null
},
"current_addresses": [
{
"id": "Location.5c80fbd1-5e5a-4356-9725-5492e3942091",
"location_type": "Address",
"street_line_1": "210 2nd St",
"street_line_2": null,
"city": "Mounds",
"postal_code": "62964",
"zip4": "1144",
"state_code": "IL",
"country_code": "US",
"lat_long": {
"latitude": 37.113098,
"longitude": -89.200842,
"accuracy": "RoofTop"
},
"is_active": true,
"delivery_point": "POBoxThrowback",
"link_to_business_start_date": "2016-11-19"
}
],
"historical_addresses": [],
"phones": [
{
"id": "Phone.46c16fef-a2e1-4b08-cfe3-bc7128b6e19a",
"phone_number": "+16187459424",
"line_type": "Landline"
}
],
"associated_people": [],
"associated_businesses": [
{
"id": "Business.e43f1c0d-ecec-42da-ad1c-76badfdf2dcf",
"name": "Usda Rural Development",
"industry": [
"Administration of Housing Programs, Urban Planning, and Community Development"
],
"relation": "Household"
}
]
},
答案 0 :(得分:0)
遍历phones
数组时,需要创建一个单独的循环。由于json.business.length
为15,因此i
会一直上升到14。但是,phones.length
只有1,因此phones[14]
会抛出错误。
使用以下代码:
for(var i=0; i < json.business.length; i++ ){
console.log(json.business[i].name);
console.log(json.business[i].found_at_address.street_line_1);
for (var x = 0; x < json.business[i].phones.length; x++) {
console.log(json.business[i].phones[x].phone_number);
}
}
注意:一种更好的方法是使用.forEach()
循环。这基本上遍历了整个数组,并且比for
循环要容易得多。
json.business.forEach(business => {
console.log(business.name);
console.log(business.found_at_address.street_line_1);
business.forEach(phones => {
console.log(phones.phone_number);
}
})
.forEach()
循环基本上完成了for
循环的工作,但是在这种情况下,business
将是json.business[i]