Assigning n-1 is a problem, because n-1 might have already been present in the array.
Instead , try to generate another random number for position 'i'.
But the for loop increments the value of 'i' in the next iteration .

Though I have never tried this by myself here might be a possible solution.

else {
i--;
continue; }

Consider that you have already generated the same number for position 3.

with i-- the value of i is 2. The for loop then increments the value and gets back to 3.

So it generates the number and checks again if the number has already been generated. If no, It would just store it in position 3 and continue.