How to select a random items from an array javascript

Опубликовано: 30 Март 2026
на канале: Profu' de geogra'
11
0

Fixed set of images: The dogImages array contains a list of image file paths (e.g., "dog1.jpg", "dog2.jpg", "dog3.jpg", and "dog4.jpg"). This array is a fixed set because the images are pre-defined in the array. We already know the images we want to use, and the JavaScript will choose one randomly from this list.
Think of this array as a collection of 4 images. But instead of manually selecting one of them, we want the browser to pick a random one each time.

Generating a Random Index with Math.random() and Math.floor():

Goal: We want to select a random image from the array, but arrays are zero-indexed. This means we need to generate a random number between 0 and 3 (because there are 4 items in the array, and their indices range from 0 to 3).How Math.random() works:

Math.random() generates a random decimal number between 0 (inclusive) and 1 (exclusive). For example, Math.random() could return 0.4567, 0.9876, 0.1234, etc.

Multiplying by the length of the array:

We multiply this random decimal by the length of the array (dogImages.length). Since the array has 4 elements, multiplying by 4 will scale the random number to a range between 0 (inclusive) and 4 (exclusive). So, we get a number between 0 and 4, but not exactly 4.For example, Math.random() might return 0.75. If we multiply it by 4, we get 3.0.

Using Math.floor():

The Math.floor() function rounds down any decimal value to the nearest whole number. So, Math.floor(3.0) would give 3, and Math.floor(0.75 * 4) gives 2. The result is always an integer between 0 and 3, which corresponds to the valid indices of the array.Using the Random Index to Update the Image:

Selecting a random image: Once we have the random index, we use that index to pick an image from the dogImages array. For instance, if the random index is 2, then dogImages[2] would be "dog3.jpg".