我是否需要添加属性才能获得所需的输出?

时间:2017-03-20 04:41:16

标签: javascript arrays

我有三个我想要的输出中的一个(第二个测试),但无法弄清楚如何获得另外两个。我也在下面列出了测试代码。

function car(gas, mpg) {
  this.gas = gas;
  if (this.gas <= 0) {
    this.empty = true;
  }
  this.mpg = mpg;
  //this.range = gas * mpg;
  //this.empty = empty;

  this.drive = function(miles) {
    this.gas -= miles / this.mpg;
    if (this.gas <= 0) {
      this.empty = true;
    }
  };

  this.fill = function(gallons) {
    if (this.gas <= 0) {
      this.fill = false;
    }
  };
}
//test code

var test = new car(15, 30);
console.log(test.empty); //expected output = false

test.drive(500);
console.log(test.empty); //expected output = true

test.fill(20);
console.log(test.empty); //expected output = false

2 个答案:

答案 0 :(得分:1)

最重要的是,编程是关注逻辑和细节。

如果您从未将false设置为empty,则empty不会获得false,因此您的第一个console.log无效你从未将empty设置为任何东西。

您的第二个console.log确实显示true,因为drive已为true条件正确设置this.gas <= 0

您的第三个不是因为(这是详细信息的来源)您设置了属性fill,而不是empty

由于empty只是gas状态的反映,您可以考虑使用 getter ,这样您就不必管理empty了所有。在car

Object.defineProperty(this, "empty", {
    get: function() {
        return this.gas <= 0;
    }
});

此外,永远不应允许gas为否定,因此您可能希望drive执行此操作:

this.gas = Math.max(0, this.gas - miles/this.mpg);

...如果你想开得太远,会将this.gas设置为0。您可能会考虑让drive计算出在燃气耗尽之前实际走了多远并将其返回,因此来电者知道您实际上没有按要求开车......

旁注:JavaScript中的压倒性的约定是构造函数的功能,如car以大写字母开头:Car

答案 1 :(得分:0)

你缺少else语句。

{{1}}
相关问题