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

I am trying to colorize the display of a canvas text object based on its value. For some reason, the previous code has the following behavior:

  • When h = 100, it displays green. This is correct.
  • When h < 100, it displays yellow. This is correct.
  • When h < 75, it SHOULD display red. It displays yellow.

Console.log shows:

    70
    yellow:  70 >= 75.

But 70 is obviously less than 75, so why isn't the console displaying "red"?

Why?

3
  • 1
    you have to update your if statements and use some && for example: (75 <= h && h < 100) Commented Dec 18, 2015 at 7:18
  • Yes, using && returns the correct code. But when I put the code through jshint.com without the &&, it didn't flag the statements as incorrect. That seems very strange to me. Commented Dec 18, 2015 at 7:19
  • 2
    everything after 75 <= h got ignored u cant do 2 comparisons without saying that you really want to do 2 of them since 75 is smaller than h each time it will be yellow :) Commented Dec 18, 2015 at 7:21

2 Answers 2

3

try to use if like this

(h >= 75 && h < 100)
(h >= 25 && h < 75)
Sign up to request clarification or add additional context in comments.

1 Comment

The second parts of both of those expressions are redundant - those cases are already handled by the previous conditional block
1

Change your code to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.