Javascript 我是否需要添加属性以生成所需的输出?
我得到了三个期望输出中的一个(第二个测试),但不知道如何得到另外两个。我还包括了下面的测试代码Javascript 我是否需要添加属性以生成所需的输出?,javascript,arrays,Javascript,Arrays,我得到了三个期望输出中的一个(第二个测试),但不知道如何得到另外两个。我还包括了下面的测试代码 功能车(汽油,每加仑){ 这个。气体=气体; 如果(this.gas您缺少else语句 function car(gas, mpg) { this.gas = gas; if (this.gas <= 0){this.empty = true;} else{this.empty = false;} this.mpg = mpg; //this.rang
功能车(汽油,每加仑){
这个。气体=气体;
如果(this.gas您缺少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;}
};
}
功能车(汽油,每加仑){
这个。气体=气体;
如果(this.gas比其他任何东西都重要,那么编程就是密切关注逻辑和细节
如果从未将empty
设置为false
,则不会得到false
的empty
,因此您的第一个控制台.log
无法工作,因为您从未将empty
设置为任何值
您的第二个console.log
确实显示true
,因为drive
为this.gas正确设置true
。该代码中没有数组。我已将您的代码移到可运行的堆栈片段中,并将console.log
替换为警报。而不是如果(条件){value=true;}否则{value=false;}
,只需使用value=condition;
非常感谢这有助于分配!
Object.defineProperty(this, "empty", {
get: function() {
return this.gas <= 0;
}
});
this.gas = Math.max(0, this.gas - miles/this.mpg);