如果/ if else逻辑在javascript中

时间:2015-12-18 07:15:50

标签: javascript if-statement logic conditional

var h = game.ship.hull.hullIntegrity(); //returns int from 0-100
var hstr = h.toString()+"%";
gcp.hullIntegrity.text = hstr;
gcp.hullHealth.text = game.ship.hull.health;
//colorize data
console.log(h);
if (h === 100) {
    gcp.hullIntegrity.addColor("#05AA0D",0);
} else if (75 <= h < 100) {
    console.log("yellow: ", h + " >= 75.");
    gcp.hullIntegrity.addColor("#FFEC0D",0);
} else if (25 <= h < 75) {
    console.log("red:", h + " < 75.");
    gcp.hullIntegrity.addColor("red",0);
} else if (h < 25) {
    console.log("grey");
    gcp.hullIntegrity.addColor("grey",0);
}

我正在尝试根据其值来着色画布文本对象的显示。出于某种原因,前面的代码具有以下行为:

  • 当h = 100时,显示绿色。这是对的。
  • 当h < 100,它显示黄色。这是对的。
  • 当h < 75,它应该显示红色。它显示黄色。

Console.log显示:

    70
    yellow:  70 >= 75.

但是70显然小于75,所以为什么控制台没有显示&#34; red&#34;?

为什么?

2 个答案:

答案 0 :(得分:3)

试着像这样使用

(h >= 75 && h < 100)
(h >= 25 && h < 75)

答案 1 :(得分:1)

将您的代码更改为

var h = game.ship.hull.hullIntegrity(); //returns int from 0-100
var hstr = h.toString()+"%";
gcp.hullIntegrity.text = hstr;
gcp.hullHealth.text = game.ship.hull.health;
//colorize data
console.log(h);
if (h === 100) {
   gcp.hullIntegrity.addColor("#05AA0D",0);
} else if (h >= 75 && h < 100) {
   console.log("yellow: ", h + " >= 75.");
   gcp.hullIntegrity.addColor("#FFEC0D",0);
} else if (h >= 75 && h < 100) {
   console.log("red:", h + " < 75.");
   gcp.hullIntegrity.addColor("red",0);
} else if (h < 25) {
   console.log("grey");
   gcp.hullIntegrity.addColor("grey",0);
}
相关问题