-3

I created a simple fuzzbuzz in javascript (see below). I however would like to include the following:

  • if the number starts with a 1 (so fe 11) "ping" should be added. So 15 should be FizzBuzzPing etc...

Any thoughts?

function fizzBuzz() {

   for (var i=1; i <= 20; i++)
    {
      if (i % 15 == 0)
          alert("FizzBuzz");
      else if (i % 3 == 0)
          alert("Fizz");
      else if (i % 5 == 0)
          alert("Buzz");
      else
         alert(i);
   }
}


$(document).ready(function(){ 
   $('#clickMe').click(function(){
      fizzBuzz();     
   });  
});
MixedVeg
  • 319
  • 2
  • 15
user3706202
  • 197
  • 1
  • 3
  • 14
  • Convert the number to a string and test the first character? Also, should "Ping" be output for _all_ numbers that start with a 1, or just the numbers that already have some other output because they match one of the other conditions? – nnnnnn Dec 05 '14 at 13:03
  • "Any thoughts?" --- add it. – zerkms Dec 05 '14 at 13:03
  • what effort have you made to solve your new problem, not just what you have done. – Daniel A. White Dec 05 '14 at 13:04
  • @zerkms Sorry missed the line about "Ping" , what is required thing please explain I cannot comprehend it. – MixedVeg Dec 05 '14 at 13:16

1 Answers1

1

Convert the number to a string and take the first index of the string:

var digit = (''+i)[0];

Or, the alternative

var digit = i.toString()[0];

Then check if digit is equal to 1 or not and add things or not accordingly.

For a future reference: Spend some time searching for a solution to your problems, don't ask questions unless you've spent some time making sure an answer does not exist to your question. A similar question has been answered many times before. Maybe it's not about fuzzbuzz but you should be able to find two different answers to two different questions and be able to combine then into your solution.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • Btw, it's a strange decision to use tricky `('' + int)` conversion when a nice and readable `.toString()` is available. – zerkms Dec 05 '14 at 13:10
  • @zerkms Some will [disagrees](http://stackoverflow.com/questions/13955738/javascript-get-the-second-digit-from-a-number) with you but sure it's an alternative, just a matter of preference. Added it to the answer nevertheless :) – Jonast92 Dec 05 '14 at 13:18