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

JavaScript计算轨道周期时无法正确获取对象属性值的问题

问题排查:无法获取对象数组中avgAlt属性值

我正在编写一段JavaScript代码,接收输入的对象数组,经过一系列计算后返回替换了第二个键值对的新对象数组。目前计算逻辑正确,但在第二步计算中无法正确获取对象的avgAlt属性值,console.log(arr.avgAlt)返回undefined而非预期数值,反复核对仍未找到问题,请求帮助排查。

代码如下:

function orbitalPeriod(arr) {
  const GM = 398600.4418;
  const earthRadius = 6367.4447;

//Step 1: get two times pi
let stepOne = 2 * Math.PI;

//Step 2: find a appears to be e radius + avg alt
/*the issue is in this line. I know I am calling the avgAlt wrong, but I'm not sure how it is wrong. 
The console log returns undefined, but it should be returning a number */ 
let stepTwo = earthRadius + arr.avgAlt;

console.log(arr.avgAlt);

//Step 3: get a^3
let stepThree= Math.pow(stepTwo, 3);

//Step 4: divide step 2 by GM defined above
let stepFour= stepTwo/GM;

//Step 5: Combo it all and round to find t
let t = Math.round(stepOne*stepFour);

//return the array w/ the new key/value pair & t is the value
 let newArr= arr.map(function(el){
    return {name:el.name,
            orbitalPeriod: t}          
  });

  return newArr;
};
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);   

问题原因

你犯了基础的数组访问错误:函数参数arr是对象数组,数组本身并没有avgAlt属性,只有数组里的每个对象才有这个属性。直接写arr.avgAlt自然会返回undefined。

另外你的轨道周期计算公式也有误,正确的公式是:
轨道周期 = 2π × √(a³/GM)
其中a是地球半径+平均高度,你之前的代码没有正确使用三次方和平方根的计算逻辑。

修正后的代码

function orbitalPeriod(arr) {
  const GM = 398600.4418;
  const earthRadius = 6367.4447;

  // 遍历数组中的每个对象,单独计算轨道周期
  return arr.map(el => {
    const a = earthRadius + el.avgAlt;
    const orbitalPeriod = Math.round(2 * Math.PI * Math.sqrt(Math.pow(a, 3) / GM));
    return { name: el.name, orbitalPeriod };
  });
};

// 测试调用
console.log(orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]));

关键修改点

  • 将计算逻辑移到map回调函数内部,针对数组中的每个对象el获取el.avgAlt,而非在数组本身上查找该属性
  • 修正轨道周期计算公式,正确实现2π × √(a³/GM)的逻辑
  • 用箭头函数简化代码结构,保留原有功能的同时提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:35:25