Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
¿Qué debo agregar a este código para evitar que las imágenes generadas aleatoriamente se repitan?

Hola, he intentado encontrar una solución a esto y estoy luchando. ¡Soy muy nuevo en Javascript! Este código funciona para generar una imagen aleatoria al hacer clic en el botón, pero las imágenes se repiten aleatoriamente. Quiero mostrar todas las imágenes pero sin repetir imágenes ya mostradas. Entiendo que debería agregar un bucle for y una declaración if, pero no sé cómo escribirlo. Estas son solo algunas imágenes de ejemplo en la matriz, en realidad tendré 55 imágenes al final. ¿¡Alguien puede ayudarme!? ¡Gracias! :)

Código actual:

 const imageArray = [ "https://images.unsplash.com/photo-1508185159346-bb1c5e93ebb4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=55cf14db6ed80a0410e229368963e9d8&auto=format&fit=crop&w=1900&q=80", "https://images.unsplash.com/photo-1495480393121-409eb65c7fbe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=05ea43dbe96aba57d48b792c93752068&auto=format&fit=crop&w=1351&q=80", "https://images.unsplash.com/photo-1501611724492-c09bebdba1ac?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ebdb0480ffed49bd075fd85c54dd3317&auto=format&fit=crop&w=1491&q=80", "https://images.unsplash.com/photo-1417106338293-88a3c25ea0be?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=d1565ecb73a2b38784db60c3b68ab3b8&auto=format&fit=crop&w=1352&q=80", "https://images.unsplash.com/photo-1500520198921-6d4704f98092?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ac4bc726064d0be43ba92476ccae1a75&auto=format&fit=crop&w=1225&q=80", "https://images.unsplash.com/photo-1504966981333-1ac8809be1ca?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=9a1325446cbf9b56f6ee549623a50696&auto=format&fit=crop&w=1350&q=80" ]; const image = document.querySelector("img"); const button = document.querySelector("button"); window.onload = () => generateRandomPicture(imageArray); button.addEventListener("click", () => generateRandomPicture(imageArray)); function generateRandomPicture(array){ let randomNum = Math.floor(Math.random() * array.length); image.setAttribute("src", array[randomNum]); }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Esto debería explicar claramente cómo hacer esto utilizando detectores de eventos y el conocido algoritmo aleatorio de Fisher-Yates . Si el primer elemento de la matriz mezclada coincide con la imagen actual, la reproducción aleatoria se repite (a través de un ciclo do- while) para evitar mostrar la misma imagen dos veces seguidas.

 window.addEventListener('DOMContentLoaded', () => { // Identifies DOM elements and other constants const changeButton = document.getElementById("change-button"), displayDiv = document.getElementById("display-div"), imageArray = ["image 1", "image 2", "image 3", "image 4", "image 5"], HIGHEST_INDEX = imageArray.length - 1; // Calls `changeImage` whenever changeButton is clicked changeButton.addEventListener("click", changeImage); // Forces shuffle on first click let currentIndex = HIGHEST_INDEX; // Defines listener for click events function changeImage(){ // If we're at the end of the array, we need to shuffle... if(currentIndex == HIGHEST_INDEX){ // Remembers the current image const currentImage = imageArray[currentIndex]; // Keeps calling `shuffle` until next image ≠ current image do { shuffle(imageArray); } while (imageArray[0] === currentImage); // Prepares to start from beginning of shuffled array currentIndex = -1; } //Regardless, increments index and shows corresponding image displayDiv.textContent = imageArray[++currentIndex]; } // Implements Fisher-Yates shuffle function shuffle(arr, randIndex=NaN, temp=null){ // Starts i at the highest index & works backwards through array let i = arr.length - 1; while(i-- > 0){ // Gets random index from remaining (unswapped) indexes rand = Math.floor(Math.random() * (i + 1)); // Swaps the value at the random index with the value at i temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } } });
 #display-div {margin-top: 0.5em; }
 <button id="change-button">CHANGE IMAGE</button> <div id="display-div"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Creo que esto es más como lo que estabas tratando de hacer. (Mi otra respuesta permitía recorrer la misma lista repetidamente y aleatorizarla cada vez, pero para el bingo no necesitas todo eso).

La función populateImgs toma una lista de direcciones URL y recorre todos los elementos img en la página, configurando cada atributo src en una dirección URL diferente o fallando si hay muy pocas direcciones URL para llenar todas las imágenes. Cuando se llama a la función, el argumento urls se construye sobre la marcha a partir de una lista mezclada de urls parciales. (Las URL resultantes son más cortas que las URL originales, que incluían muchos parámetros que omití por razones de brevedad).

La función de shuffle utiliza el mismo algoritmo pero se implementa de forma un poco diferente (usando el while(--i > 0){ swap(array, i, randLessThan(i)); } ) de apariencia más limpia.

 window.addEventListener('DOMContentLoaded', function(){ // Defines an array of strings that identify photos const photoIds = [ "1508185159346-bb1c5e93ebb4", "1495480393121-409eb65c7fbe", "1501611724492-c09bebdba1ac", "1417106338293-88a3c25ea0be", "1500520198921-6d4704f98092", "1504966981333-1ac8809be1ca" ]; // Calls `populateImgs`, w/ a list of randomized urls based on photoIds populateImgs( shuffle(photoIds).map(id => `https://images.unsplash.com/photo-${id}`) ); function populateImgs(urls){ // Shows one photo in each img element const imgs = document.querySelectorAll("img"); if(urls.length < imgs.length){ return console.log("Not enough photos"); } let index = -1; while (++index < imgs.length){ imgs[index].setAttribute("src", urls[index]); }; } function shuffle(array){ // Uses helper functions to randomize array, returns randomized array const randLessThan = (num) => Math.floor(Math.random() * num), swap = (arr, i, rand) => { let temp=arr[rand]; arr[rand]=arr[i]; arr[i]=temp; }; // Iterates backwards, swaps each item with a random earlier item, ignores i==0 let i = array.length; while(--i > 0){ swap(array, i, randLessThan(i)); } return array; } });
 img{ width: 100px; height: 80px; object-fit: cover; margin: 15px; }
 <div class="row"> <img/><img/> </div> <div class="row"> <img/><img/> </div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda