How to generate 5 different random numbers?

I tried to generate 5 different random numbers in a for loop to generate 5 images, but 5 random numbers are generated exactly the same! var numberOfFaces = 5;

var theLeftSide = document.getElementById("leftSide");

for (var i = 0; i < numberOfFaces; i++) {

    //create image

    var img = document.createElement('img');

    img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";

    var random1 = Math.floor(Math.random() * 500 - (100 * i));

    var random2 = Math.floor(Math.random() * 500 - 100 * i);

    img.style.top = random1;

    img.style.left = random2;

    document.body.appendChild(img);

}
+4
source share
2 answers

Not that random numbers are not random, but to set the css values ​​you need a unit like pixels, percent, etc.

img.style.top = random1 + 'px';
img.style.left = random2 + 'px';

And for these CSS values ​​to take effect, the elements must have a different position than static

img.style.position = 'absolute';

Fiddle

+8
source

(Sir checks the random number generation instruction)

There are several examples on the Mozilla Developer page :

/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
+1

Source: https://habr.com/ru/post/1613082/


All Articles