调用子功能

时间:2015-12-29 05:00:30

标签: javascript

这是一个找到第n个斐波纳契数的程序。

var fib = (function() {
    var save = [];
    var i = 0;

    return {
        "getNum": function(input) {
            this.input = input;

            if (input === 0) {
                console.log("Invalid input");
            }

            save[i] = i;
            save[i + 1] = i + 1;
            save[i + 2] = i + 1;
            i = 2;

            for (i >= 2; i < input; i = i + 1) {
                save[i + 1] = save[i] + save[i - 1];
            }

            console.log(save[i - 1]);
        }
    }
}());

fib.getNum(4);

我的问题是,当我以下列方式实现此问题时,它无法正常工作。我理解这是因为我没有调用子函数而只调用main函数。我们可以使用哪种更好的模式来保持代码的有序性,我们不必调用这么多函数吗?

var fib = (function() {
    var save = [];
    var i = 0;

    return {
        "getNum": function(input) {
            this.input = input;

            function valid() {
                if (input === 0) {
                    console.log("Invalid input");
                }
            }

            function config() {
                save[i] = i;
                save[i + 1] = i + 1;
                save[i + 2] = i + 1;
                i = 2;
            }

            function nthNum() {
                for (i >= 2; i < input; i = i + 1) {
                    save[i + 1] = save[i] + save[i - 1];
                }
                console.log(save[i - 1]);
            }
        }
    }
}());

fib.getNum(4);

2 个答案:

答案 0 :(得分:0)

我的建议:

&#13;
&#13;
def Fights(self):
    fights = []
    for fight in self.fighter["Fights"]:
        fights.append(dict(Opponent=str(fight["Opponent"]),
                           Location=str(fight["Location"]),
                           Date=(fight["Date"]),
                           Result=str(fight["Result"]),
                           Round=str(fight["Round"]),
                           Time=str(fight["Time"]),
                           Win=str(fight["Win"])))

    return fights
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以考虑使用closure创建私有和公共函数。如果您看到以下代码,则只显示_getNum函数。

var fib = (function() {
    var save = [];
    save[0] = 0;
    save[1] = 1;
    var i = 0;

    //This will validate the number
    // This function can be avoided and make _getNum do the same

    function _valid(input){
      console.log("Method Executing:_valid");
      input === 0 ? console.log('Invalid Input') : _nthNum(input); 
     }

    // Will calualte the series.
    // This is a private function
    function _nthNum(input) {
     console.log('Method Executing:_nthNum');
        for (i = 2; i<=input; i++) {
             save[i] = save[i-2] + save[i - 1];
         }
          console.log(save.pop());
    }

    // Private Function
    function _getNum(input){
            console.log("Method Executing :_getNum" ,input);
            _valid(input);
        }

    //Expose the private function
  return {
   getNum :_getNum      // Expose _getNum
  }
}());
fib.getNum(0);
fib.getNum(4);
fib.getNum(7);

WORKING COPY