2017-03-20 38 views
0

我有三个我期望的输出(第二个测试)中的一个,但无法弄清楚如何得到另外两个。我也包含下面的测试代码。我是否需要添加属性才能生成所需的输出?

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

我已将您的代码移至* runnable * Stack Snippet,并将'console.log'替换为'alert'。 –

回答

1

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

你不会得到falseempty,如果你从来没有设置emptyfalse,使你的第一个console.log不工作,因为你从来没有设置empty任何东西。

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

你的第三个并不是因为(这是细节进来的地方),你正在设置属性fill,而不是empty

由于empty只是一个gas状态的反射,你可以考虑使用一个吸气所以你不必管理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.gas0,如果你想驾驶太远。你可能会考虑让drive算多远,你居然跑出来的气体和返回之前去了,所以调用者知道你实际上并没有驾车到请求......


边注:压倒性 JavaScript中的约定是像你的car这样的构造函数以大写字母开始:Car

+0

非常感谢这有助于分配! –

0

你缺少与else语句。

function car(gas, mpg) { 
    this.gas = gas; 
    if (this.gas <= 0){this.empty = true;} 
    else{this.empty = false;} 
    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; 
    }else{ 
    this.empty = false; 
    } 
    }; 

    this.fill = function (gallons){ 
    if (this.gas <=0) { 
    this.fill = false;} 
    else{this.fill = true;} 
    }; 
    } 
+2

而不是'if(condition){value = true; } else {value = false; }',只需使用'value = condition;' –

相关问题