In: Computer Science
Consider the series of numbers beginning at start and running up through end inclusive. For example start=4 and end=8 gives the series 4, 5, 6, 7, 8. Write a complete JavaScript function named fizzBuzz (including a function heading) that returns a new array containing the number, except for multiples of 3, use "Fizz" instead of the number. For multiples of 5 use "Buzz". For multiples of both 3 and 5 use "FizzBuzz".
The following code must print the output that follows the code:
array = fizzBuzz(8, 16);
for(var i = 0; i < array.length; i++) {
console.log(array [i])
}
Output:
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
HTML & Javascript:
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript">
//Function that
runs when page is loaded
function run()
{
//Calling function
array = fizzBuzz(8, 16);
//Iterating over array
for(var i = 0; i < array.length; i++) {
//Printing results
console.log(array [i]);
}
}
//Function definition
function
fizzBuzz(start, end) {
//Array declaration
var fizzB = [];
//Iterating over range
for(var i = start; i <= end; i++) {
//Checking for multiples of 3
& 5
if(i%3==0 && i%5==0)
{
//Adding
word FizzBuzz
fizzB.push("FizzBuzz");
}
//Checking for multiples of
3
else if(i%3==0) {
//Adding
word Fizz
fizzB.push("Fizz");
}
//Checking for multiples of
5
else if(i%5==0) {
//Adding
word Fizz
fizzB.push("Buzz");
}
//Pushing number
else {
fizzB.push(i);
}
}
return fizzB;
}
</script>
</head>
<body onload="run()">
</body>
</html>
______________________________________________________________________________________
Sample Run: