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

JS中for..in循环返回undefined,如何仅获取目标值Tom

问题原因

你遍历了obj对象的所有可枚举属性,obj包含minute和ads两个顶级属性:

  • minute属性下存在product数组,所以能取到Tom
  • ads属性是空对象,没有product属性,访问product[0]自然返回undefined

解决方法

方法1:明确知道要取minute下的属性,直接取值(性能最优)

不用遍历全对象,直接定位到目标属性即可:

console.log(obj.minute.product[0])

方法2:遍历全对象时加合法性判断

如果需要遍历所有属性筛选有product的项,提前判断属性存在性再取值:

for(let entry in obj){
  const current = obj[entry]
  // 先判断product存在、是数组且长度不为0再取值
  if(current.product && Array.isArray(current.product) && current.product.length) {
    console.log(current.product[0])
  }
}

方法3:用可选链简化判断(ES2020及以上环境支持)

for(let entry in obj){
  const res = obj[entry].product?.[0]
  if(res !== undefined) console.log(res)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:12:02