0

I am calling the function below. The log that I am receiving when I input the number 7. The log shows the values 71, 8, 9, 10, 11. I am assuming it has something to do with treating i as a string and then a number. To combat it I tried the Number() method. Same Log with and without the Number() method

function hideCoasterQuantity(number) {
  for (var i = number; i < 11; i++) {
    var hideVal = Number(i + 1);
    $("#coasteremblem-" + hideVal).hide();
    console.log("hide coaster " + hideVal);
    $("#coasteremblemtitle-" + hideVal).hide();
  }
  console.log("hideCoasterQuantity completed");
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
  • I created a similar function called showCoasterQuantity and it functions perfectly fine. But this one is giving me issues! – Trey Smith Oct 16 '20 at 15:37
  • Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – VLAZ Oct 16 '20 at 15:39
  • Your `number` input is in fact a string. You need to parse it into an actual number first `number = Number(number)` – VLAZ Oct 16 '20 at 15:40
  • @VLAZ It kind of did. But it did some sort of type conversion after the first loop. Does not matter now that it is written properly but it is rather strange. – Trey Smith Oct 16 '20 at 17:17
  • Yes, `i++` would increment the value, which implicitly converts it to a number. – VLAZ Oct 16 '20 at 17:31

1 Answers1

0

Make sure the caller of hideCoasterQuantity calls it with a number, eg:

hideCoasterQuantity(Number(someInputValue));

That'll fix the problem and let you remove the numeric casting inside hideCoasterQuantity:

var hideVal = i + 1;

But adding 1 to the index inside the loop is strange, why not just start from i + 1 to start with?

function hideCoasterQuantity(number){
  for(let hideVal = number + 1; hideVal < 12; hideVal++) {
    $("#coasteremblem-" + hideVal).hide();
    $("#coasteremblemtitle-" + hideVal).hide();
  }
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you! I have no excuse for my poor structure. I still find it very odd that it treated it as a string 1 time around and not any time after. – Trey Smith Oct 16 '20 at 17:13