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

JS使用map遍历对象数组提取属性值返回undefined问题排查

问题原因及修复方案

核心错误点

  • 对象属性访问方式错误
    你遍历的data数组每一项都是对象类型,并非数组,你写的d[3]是试图取下标为3的数组元素,普通对象没有数字索引自然返回undefined,需要用对象属性访问语法取值。
  • 未定义close变量
    后续调用sma指标时传入的close变量没有提前定义,运行到此处会抛出引用错误,需要提前提取close数组。
  • catch回调语法错误
    .catch(console.error())是立即执行console.error方法,而非将函数作为回调传入catch,需要去掉括号传递函数引用。
  • 语法闭合错误
    代码中then回调的大括号位置错误,注释代码被写在了回调函数的闭合大括号外部,需要调整括号位置保证逻辑代码都在回调内部。

修复后代码

// Data from CCompare
CryptoCompareAPI.histoHour('BTC', 'USD')
.then(data => { 
  data = data.reverse()
  console.log(data)
  // 正确提取open属性
  const open = data.map(d => d.open)
  console.log(open)
  // 提前提取需要的close数组
  const close = data.map(d => d.close)
 
  tulind.indicators.sma.indicator([close],[3],(error,res) => {
     if (error) return console.log(error)
     console.log(res)
  })
  // 注释代码放在回调内部
  //console.log("high",data[i].high)
  //console.log(data.length)
})
// 修正catch回调写法
.catch(console.error)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:54:04