我有三个我想要的输出中的一个(第二个测试),但无法弄清楚如何获得另外两个。我也在下面列出了测试代码。
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
答案 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}}