dart递归类方法总是返回null

时间:2012-08-05 02:23:26

标签: javascript recursion dart

这似乎不可能用飞镖?即让一个类方法递归并最终返回一个对象?当我运行一个递归方法时,如果它至少递归一次,它总是返回null ...

示例:

// some class method
rock throw_rock() {
  // look at its own collection of rocks
  // get a rock and do a test on it
  rock to_throw = this.rocks[53]; // lets assume its in a map at key 53...
  if (to_throw.been_thrown == 1) {
    // ok, dont throw this one, instead recurse and find another
    this.throw_rock();
  } else {
     return to_throw;
  }
}

在其他课程或主要课程中:

rock g = rock_thower.throw_rock();
// if rock thrower has had to recurse
// g will be null...

我对飞镖很新,不知道为什么会这样。有任何想法吗?这是理智的吗?

如果没有:我做错了什么?

2 个答案:

答案 0 :(得分:4)

需要return this.throw_rock()

也就是说,您想要返回to_throw变量或递归调用的结果。

答案 1 :(得分:0)

您使用递归的原因是什么?看起来像do / while可能会起作用:

// some class method
rock throw_rock() {
  rock to_throw;
  do {
    // look at its own collection of rocks
    // get a rock and do a test on it
    to_throw = this.rocks[53]; // lets assume its in a map at key 53...
  } while (to_throw.been_thrown != 1);
  return to_throw;
}

与递归方法一样,当所有岩石都不能被抛出时,你需要一个退出条件来处理这个案例。