当我在提示符0处输入时,我希望收到警报“停止”,但收到“执行”。您能帮我得到警报“停止”吗?



var toyota = {
  make: "Toyota",
  model: "Corolla",
  fuel: 0,
  tank: function(addingfuel) {
    this.fuel = this.fuel + addingfuel;
  },
  start: function() {
    if (this.fuel === 0) {
      alert("stop");
    } else {
      alert("go");
    }
  },
};
var addingfuel = prompt("Please enter fuel added", "liter");
toyota.tank();
toyota.start();

最佳答案

您需要稍微更改一下代码

var toyota = {
  make: "Toyota",
  model: "Corolla",
  fuel: 0,
  tank: function(addingfuel) {
    this.fuel = this.fuel + (addingfuel || 0);
  },
  start: function() {
    if (this.fuel === 0) {
      alert("stop");
    } else {
      alert("go");
    }
  },
};


说明
当您在调用toyota.tank()时不传递任何内容时,这会将参数设为undefined,并在undefined后面加上数字将为您提供NaN

0 + undefined

08-25 20:40