Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FizzBuzz into array with javascript into an array not working properly

This is my first question so sorry if it’s dumb. I’m trying to do the classic FizzBuzz exercise in the console using javascrypt, putting the changes into an array for 1 to 100. So far:

let nums = [];

for (let i = 1; i <= 100; i++) {
    nums.push(i);
}

for (num of nums) {
    if (nums[num] % 5 === 0) {
        nums[num] = "Buzz";
        console.log("Buzz");
    }
    else if (nums[num] % 3 === 0) {
        nums[num] = "Fizz";
        console.log("Fizz");
    }
    else if (nums[num] % 3 === 0 && nums[num] % 5 === 0) {
        nums[num] = "FizzBuzz";
        console.log("FizzBuzz");
    }
    else {
        console.log(nums[num]);
    }

}

I’m expecting each FizzBuzz to be put into the array instead of the number, and all the array to be printed on the console. But for some specific numbers it doesn’t work. When two vales need to be changed consequently, the second one gives some kind of error. What am i missing?

Thanks for your help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue is that you’re counting starts at 1, and you’re using that number as an index. First entry in the array is nums[0] but you’re using nums[num] where num==1 so you’re getting nums[1] as the first entry.

So first entry is:

num == 1
nums[1] == 2  // as nums[0] == 1

then next

num == 2
nums[2] == 3, so replace with Fizz

now next entry in the array is nums[2] (0,1 above) and nums[2] == Fizz (replaced above)

num == "Fizz"
nums["Fizz"] == undefined

There are two fixes:

  1. start at 0
  2. use for of

Starting at 0 means your num is the same as the index and you’re not replacing the "next" value with fizz/buzz. The problem is you have to start at 0.

Using for of means you use the indexes directly instead of the values, so the position doesn’t matter – you could for example populate in your initial using with i+=10 instead of i++ to get different values.

for (num of nums) gives the values (1,2,3,"Fizz",…) and would be the same as:

for (let i=0; i<nums.length; ++i) {
    num = nums[i]

(ye-olde method before for of existed)

while for (num in nums) gives the indexes (0,1,2…) and would be the same as

for (let num = 0; num<nums.length; ++num)`

Using for of seems the appropriate solution here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading