0

我目前正在尝试将一些 ruby​​ 代码翻译成 Javascript。

这是我写的:

class Bowling {
constructor (){
    this.frame = 1;
    this.score = 0;
    this.is_spare = false;
    this.is_strike = false;
    this.is_double = false;
  }
game(ball_1, ball_2){
if(this.is_double == true){
    var frame_score = ball_1 + (ball_1 + ball_2) * 2;
}
else if(this.is_strike == true){
    if(ball_1 == 10)
    this.is_double = true;
frame_score = (ball_1 + ball_2) * 2;


}
else if(this.is_spare == true){
frame_score = ball_1 * 2 + ball_2;
}
else{
    frame_score = ball_1 + ball_2;
}

if(ball_1 == 10){
    this.is_strike = true;
    this.is_spare = false;
}
else if(ball_1 + ball_2 == 10){
    this.is_spare = true;
    this.is_double = false;
    this.is_strike = false;
}
else{
    this.is_spare = false;
    this.is_strike = false;
    this.is_double = false;
}
this.score = this.score + frame_score;

}

}

当我在一个新的保龄球对象上调用 game(1,2) 时,结果不是 3,而是未定义,我不明白为什么。

4

1 回答 1

1

发生这种情况是因为您必须这样做return this.score。如果您不这样做,则该方法不知道要返回什么,并且像许多其他编程语言一样返回undefined或类似的值。

class Bowling {
  constructor() {
    this.frame = 1;
    this.score = 0;
    this.is_spare = false;
    this.is_strike = false;
    this.is_double = false;
  }
  game(ball_1, ball_2) {
    if (this.is_double == true) {
      var frame_score = ball_1 + (ball_1 + ball_2) * 2;
    } else if (this.is_strike == true) {
      if (ball_1 == 10)
        this.is_double = true;
      frame_score = (ball_1 + ball_2) * 2;


    } else if (this.is_spare == true) {
      frame_score = ball_1 * 2 + ball_2;
    } else {
      frame_score = ball_1 + ball_2;
    }

    if (ball_1 == 10) {
      this.is_strike = true;
      this.is_spare = false;
    } else if (ball_1 + ball_2 == 10) {
      this.is_spare = true;
      this.is_double = false;
      this.is_strike = false;
    } else {
      this.is_spare = false;
      this.is_strike = false;
      this.is_double = false;
    }
    this.score = this.score + frame_score;
        
    return this.score
  }

}

var x = new Bowling()
console.log(x.game(1, 2))

MDN指出:

要返回默认值以外的值,函数必须具有指定要返回的值的 return 语句。没有 return 语句的函数将返回默认值。在使用 new 关键字调用构造函数的情况下,默认值是其 this 参数的值。对于所有其他函数,默认返回值是未定义的。

于 2020-10-10T17:18:00.110 回答