You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS循环访问JSON对象中phones.phone_number返回undefined问题求助

问题分析与解决

你遇到的问题其实很常见——错误复用了外层循环的索引i来访问每个business下独立的phones数组。

先看你代码里的问题行:

console.log(json.business[i].phones[i].phone_number);

外层的i是用来遍历business数组的(从0到14),但每个商家的phones数组长度不一定和i匹配。比如第一个商家的phones只有1个元素,当i=1时,phones[1]根本不存在,自然返回undefined。

正确的处理方式

每个business的phones是独立的数组,得针对每个商家单独处理它的手机号列表,分两种场景:

场景1:商家可能有多个手机号(推荐遍历)

如果有的商家有多个手机号,就给每个商家的phones单独加一层循环:

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);
  // 取出当前商家的手机号列表,单独遍历
  const currentPhones = json.business[i].phones;
  for(var j=0; j < currentPhones.length; j++){
    console.log(currentPhones[j].phone_number);
  }
}

场景2:确定每个商家只有一个手机号

如果业务里每个商家肯定只有一个手机号,直接用索引0访问就行,最好再加个判空避免报错:

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);
  // 先判断手机号列表是否存在且有内容,再访问第一个元素
  if(json.business[i].phones && json.business[i].phones.length > 0){
    console.log(json.business[i].phones[0].phone_number);
  } else {
    console.log("该商家未填写手机号");
  }
}

额外提醒

加上判空逻辑能避免某些商家没有phones字段,或者phones是空数组时出现控制台报错,让代码更健壮。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:17:12