我正在处理一些JavaScript代码,这些代码应该接受一个输入的对象,然后通过一系列的方程来运行它,然后返回对象,但是将第二个键/值对替换为在函数中计算出来的一个新的键值对。我所有的数学都是正确的,但是在方程的第二步中,我错误地调用了键的值。arr.avgAlt的控制台日志在应该返回数字时返回未定义的值。我已经反复检查了我的笔记和其他在线资源,但我仍然不知道是什么问题。我觉得我好像忽略了一些显而易见的东西。
  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}]);   发布于 2022-10-01 03:51:17
在步骤2中,更改:
let stepTwo = earthRadius + arr.avgAlt至:
let stepTwo = earthRadius + arr[0].avgAlt函数参数是数组中的一个对象。因此,您需要选择数组中的对象位置,然后选择要取出的键。
https://stackoverflow.com/questions/73915660
复制相似问题