Looping through an array and replacing the items

Hey everyone, I’m trying to see what is wrong with my code here. The task is to loop throughout the array and replace certain numbers with string.

Here is the code:

let integers = [];

for ( index = 0; index < 50; index++ ){

 integers[index] = Math.round(Math.random()*50);


for (i = 0; i < integers.length; i++){

    if (integers[i] == 4) {

        integers[i] = 'Cat';


    else if (integers[i] == 7) {

        integers[i] = 'Fish';



what’s happening? why do you say that your code doesn’t work?

The code seems to work. But you are not guaranteed to get the numbers generated you are looking for. You can try logging out the array of random numbers first to see what numbers you got.

Also, just as an aside, you should declare your variables in the loops.

Thank you for the reply. It does work now!