【问题标题】:If / if else logic in javascriptjavascript中的if / if else逻辑
【发布时间】:2016-03-24 20:19:14
【问题描述】:
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
  • 当 h

Console.log 显示:

    70
    yellow:  70 >= 75.

但是70明显小于75,那为什么控制台不显示“红色”呢?

为什么?

【问题讨论】:

  • 你必须更新你的 if 语句并使用一些 && 例如:(75
  • 是的,使用 && 返回正确的代码。但是,当我通过 jshint.com 不带 && 的代码时,它并没有将语句标记为不正确。这对我来说似乎很奇怪。
  • 75

标签: javascript if-statement logic conditional


【解决方案1】:

如果喜欢就尝试使用

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

【讨论】:

  • 这两个表达式的第二部分是多余的 - 这些情况已经由前一个条件块处理
【解决方案2】:

将您的代码更改为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多