对象之间的JavaScript传递值

时间:2018-12-09 14:16:14

标签: javascript object

当我在提示符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 个答案:

答案 0 :(得分: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");
    }
  },
};

说明 当您在调用toyota.tank()时不传递任何内容时,它将接受未定义的参数,并在未附加数字的情况下添加NaN

0 + undefined

答案 1 :(得分:1)

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

this.fuel = this.fuel + addingfuel;

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

答案 2 :(得分:0)

您必须通过addingfuel函数传递tank(addingfuel),否则addingfuel包含 undefined ,因此最后它将显示 go 而不是停止

NB addingfuel的值是 string ,因此您必须像这样{{1}将其强制转换为整数 },否则您的parseInt(addingfuel)条件将失败

让我们尝试一下,

this.fuel === 0

答案 3 :(得分:0)

window. prompt返回字符串类型作为返回值。这就是为什么在将fuel(数字)添加到addingfuel(字符串)时会导致"00"而您的条件失败的原因。

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

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