【问题标题】:Trouble working out whether one attribute of an object is greater that another attribute of that object难以确定对象的一个​​属性是否大于该对象的另一个属性
【发布时间】:2014-07-13 16:18:50
【问题描述】:

我正在比较同一对象的两个属性以找出哪个更大,如果一个更大,则将另一个属性设置为 True.. 否则将其设置为 false。

这是我的功能:

country.prototype.cure = function(){
  for (var i = 0; i<this.diseases.length; i++)
  {
    console.log(this.health);
    console.log(this.diseases[i].cureLevel); 
    if (this.heatlh >= this.diseases[i].cureLevel)
  {
    this.diseases[i].cured = true;
    createDiseaseTable();
   }
    else
   {
       this.diseases[i].cured = false;
   }
 }
}

注意:this.health = 39000000 和 this.diseases[i].cureLevel = 2500000

问题是,每当我运行该函数时,尽管 this.health 较大,但它总是会错过 if 并直接转到 else...

【问题讨论】:

  • 您在实际代码中是否真的将其拼写为“heatlh”而不是“health”?
  • 是的,你是对的,我在这个函数中拼写错误......这是漫长的一天......谢谢大家!

标签: javascript object syntax


【解决方案1】:

试试这个:

country.prototype.cure = function(){
  for (var i = 0; i<this.diseases.length; i++)
  {
    var a=parseInt(this.health);
    var b=parseInt(this.diseases[i].cureLevel);
    if (a >= b)
  {
    this.diseases[i].cured = true;
    createDiseaseTable();
   }
    else
   {
       this.diseases[i].cured = false;
   }
 }
}

【讨论】:

  • parseInt 只有在属性值是字符串而不是数字时才有用;没有迹象表明在 OP 中就是这种情况,尽管这当然可能是真的。
  • 我没有看到任何其他可能的错误。我可能是错的,这就是为什么它读取尝试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多