递归调用和函数定义

时间:2015-06-15 23:28:04

标签: javascript

我正在尝试实施一个简单的编码面试问题。但是,我很难进行递归调用:

(function () {
if(typeof Algorithms === "undefined") {
  window.Algorithms = {};
}

// Write a method, digital_root(num).
// It should sum the digits of a positive integer.
// If it is greater than or equal to 10, sum the digits of the resulting number.
// Keep repeating until there is only one digit in the result, called the "digital root".
// Do not use string conversion within your method.
Algorithms.digitalRoot = function (number) {
    if (number < 10) {
        return number;
    }

    var sum = 0;
    while(number != 0) {
        sum += number % 10;
        number = Math.floor(number/10);
    }
    this.digitalRoot(sum);
};

规范如下:

 it("65,536 should return 7", function() {
    expect(Algorithms.digitalRoot(65536)).toBe(7);
  });

  it("1,853 should return 8", function() {
    expect(Algorithms.digitalRoot(1853)).toBe(8);
  });

我认为发生的事情是:Algorithms是一个以digitalRoot作为属性(特别是函数)的对象。因此,在调用Algorithms.digitalRoot(number_here)时,this应引用Algorithms。因此,我写了像this.digitalRoot(sum)这样的递归调用。有人可以纠正我不正确的想法吗?

错误如下所示:

  

digitalRoot 65,536应返回7.预期未定义为7.错误:   预计未定义为7。       at new jasmine.ExpectationResult(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:114:32)       at null.toBe(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1235:29)       在null。 (文件:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/spec/algorithms_spec.js:3:43)       at jasmine.Block.execute(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:1064:17)       at jasmine.Queue.next_(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)       at jasmine.Queue.start(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)       at jasmine.Spec.execute(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2376:14)       at jasmine.Queue.next_(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2096:31)       at jasmine.Queue.start(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2049:8)       在jasmine.Suite.execute(file:/// C:/Users/Documents/GitHub/practice-thy-algorithms/Javascript/lib/jasmine-1.3.1/jasmine.js:2521:14)

1 个答案:

答案 0 :(得分:3)

除非number < 10,否则你不会从函数中返回任何内容。这就是您获得undefined而不是7的原因。您对this的期望是正确的。

返回值this.digitalRoot(sum);

        ...

        number = Math.floor(number/10);
    }

    return this.digitalRoot(sum);
};
相关问题