Quiero imprimir una matriz de imágenes javascript en orden aleatorio, pero espero que la del medio. Quiero que esta g.jpg permanezca en sus posiciones en este momento. Todas ellas son aleatorias, cómo separar o posición absoluta de g.jpg. Creo que necesito agregar un nombre de clase diferente para g.jpg pero no sé cómo hacerlo.
<html> <head> <meta charset='utf-8'> <title></title> <style> .ppl{ width: 250px; } </style> </head> <body> <div id="root"></div> <script type="text/javascript"> const images = [ 'images/1.jpg', 'images/2.jpg', 'images/g.jpg', 'images/3.jpg', 'images/4.jpg' ] const root = document.querySelector('#root') const shuffle = ([...array]) => { let currentIndex = array.length let temporaryValue let randomIndex // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 // And swap it with the current element. temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } const shuffledImages = shuffle(images) shuffledImages.forEach(src => { const image = document.createElement('img') image.src = src image.alt = src image.classList.add('ppl') image.classList.add('pos') root.appendChild(image) }) </script> </body> </html>Parece ser una pregunta interesante. Sí, puedes hacerlo de esta manera. Lo que sugeriría es mezclar las cuatro cosas al azar y luego agregarlas.
Puede probar la siguiente lógica que escala. La única dificultad aquí es que la lista de matrices debe ser un número impar que incluya g.jpg .
// Made two arrays of variable lengths. const a1 = [1, 2, 3, 4].map(a => a + ".jpg"); const a2 = [1, 2, 3, 4, 5, 6, 7, 8].map(a => a + ".jpg"); // Check the arrays: console.log({ a1, a2 }); // Shuffle in Random Order. a1.sort(() => 0.5 - Math.random()); a2.sort(() => 0.5 - Math.random()); // Check the arrays: console.log({ a1, a2 }); // Take the first part and second part. const f1 = a1.slice(0, a1.length / 2); const f2 = a2.slice(0, a2.length / 2); const s1 = a1.slice(a1.length / 2); const s2 = a2.slice(a2.length / 2); console.log({ f1, f2, s1, s2 }); // Now combine everything: const r1 = [...f1, "g.jpg", ...s1]; const r2 = [...f2, "g.jpg", ...s2]; console.log({ r1, r2 });He agregado todos los comentarios dentro del código. Déjame saber si eso ayuda?
Una vez que haya ordenado el lado de la matriz de las cosas, renderice el HTML en función de esto.
Puede excluir el índice para barajar.
const shuffle = ([...array], keep = []) => { let i = array.length; while (i) { const r = Math.floor(Math.random() * i); i--; if (keep.includes(i) || keep.includes(r)) continue; [array[i], array[r]] = [array[r], array[i]]; } return array; } console.log(...shuffle([1, 2, 3, 4, 5], [2]));