我改变了一个变量声明的位置,它打破了这个功能。为什么?

时间:2016-12-02 03:50:19

标签: javascript

A有关于JavaScript的问题。

为什么会这样:

function orbitalPeriod(arr) {
   
   function orbitalPeriodInside(inputData) {
    const GM = 398600.4418;
    const earthRadius = 6367.4447;
    let averageAltitude = inputData.avgAlt;
    let myNewObj = {};

    let upperPartBeforePow = earthRadius + averageAltitude;
    let upperPartAfterPow = Math.pow(upperPartBeforePow, 3);
    let dividedByLowerPart = upperPartAfterPow / GM;
    let sqrt = Math.sqrt(dividedByLowerPart);
    let orbitalPeriodT = 2 * 3.14159265359 * sqrt;
    let orbitalPeriodTRound = Math.round(orbitalPeriodT);
  
    myNewObj.name = inputData.name;
    myNewObj.orbitalPeriod = orbitalPeriodTRound;

    return myNewObj;
  }
 
  let results = arr.map(function(oneObj) {
    return orbitalPeriodInside(oneObj);
  });
  console.log(results);
  return results;
}

orbitalPeriod([{name: "iss", avgAlt: 413.6},
  {name: "hubble", avgAlt: 556.7},
  {name: "moon", avgAlt: 378632.553}]);

//should return [
//{name : "iss", orbitalPeriod: 5557},
//{name: "hubble", orbitalPeriod: 5734},
//{name: "moon", orbitalPeriod: 2377399}
//].
  

为什么不这样做:

    function orbitalPeriod(arr) {
      
       let results = [];
       
       function orbitalPeriodInside(inputData) {
        const GM = 398600.4418;
        const earthRadius = 6367.4447;
        let averageAltitude = inputData.avgAlt;
        let myNewObj = {};

        let upperPartBeforePow = earthRadius + averageAltitude;
        let upperPartAfterPow = Math.pow(upperPartBeforePow, 3);
        let dividedByLowerPart = upperPartAfterPow / GM;
        let sqrt = Math.sqrt(dividedByLowerPart);
        let orbitalPeriodT = 2 * 3.14159265359 * sqrt;
        let orbitalPeriodTRound = Math.round(orbitalPeriodT);
      
        myNewObj.name = inputData.name;
        myNewObj.orbitalPeriod = orbitalPeriodTRound;

        return myNewObj;
      }
     
      results = arr.map(function(oneObj) {
        return orbitalPeriodInside(oneObj);
      });
      console.log(results);
      return results;
    }

    orbitalPeriod([{name: "iss", avgAlt: 413.6},
      {name: "hubble", avgAlt: 556.7},
      {name: "moon", avgAlt: 378632.553}]);

    //should return [
    //{name : "iss", orbitalPeriod: 5557},
    //{name: "hubble", orbitalPeriod: 5734},
    //{name: "moon", orbitalPeriod: 2377399}
    //].

唯一的区别是'let results'的声明。第二个例子 - 声明在函数的顶部,但它不起作用。 第二个函数仅返回'use strict'。为什么?

0 个答案:

没有答案