首页 文章

JavaScript-传递对象之间的值

提问于
浏览
1

当我在提示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();

4 回答

  • 1

    如果您更改此代码,它将正常工作

    this.fuel = this.fuel + addingfuel;
    

    this.fuel = this.fuel + (addingfuel || 0);
    
  • 0

    你必须用你的 tank(addingfuel) 函数传递 addingfuel 其他明智的 addingfuel 包含 undefined 所以最后它会显示 go 而不是 stop .

    N.B addingfuel 的值是 string 所以你要像_41629那样把它投射到 integer 否则你的 this.fuel === 0 条件会失败

    试试这个,

    var toyota = {
      make: "Toyota",
      model: "Corolla",
      fuel: 0,
      tank: function(addingfuel) {
        this.fuel = this.fuel + parseInt(addingfuel);
      },
      start: function() {
        if (this.fuel === 0) {
          alert("stop");
        } else {
          alert("go");
        }
      },
    };
    var addingfuel = prompt("Please enter fuel added", "liter");
    toyota.tank(addingfuel); // you need to pass this otherwise it is undefined
    toyota.start();
    
  • 0

    window. prompt 返回字符串类型作为返回值 . 这就是为什么当你将 fuel (数字)添加到 addingfuel (字符串)时,它会导致 "00" 并且您的条件失败 .

    为了解决此问题,您应该在使用该值之前将字符串转换为数字 .

    tank: function(addingfuel) {
      var numberValue = parseFloat(addingfuel, 10);
      numberValue = isNaN(numberValue) ? 0 : numberValue
      this.fuel = this.fuel + numberValue;
    }
    
  • 1

    您需要稍微更改一下代码

    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");
        }
      },
    };
    

    Explanation 当你在调用toyota.tank()时没有传递任何内容时,这会将参数视为未定义,并使用数字附加undefined会给你NaN

    0 + undefined
    

相关问题