Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Cómo obtener 4 imágenes aleatorias de una matriz de 6 imágenes en Javascript

Tengo un pequeño problema. Necesito obtener 4 imágenes aleatorias de una matriz de 6 elementos, pero no sé cómo hacerlo. Las imágenes deben repetirse.

 let array = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"]; shuffleArray(array); array.forEach(function(image) { let img = document.createElement('img'); img.src = image; img.height = "45"; img.width = "50"; document.getElementById("random").appendChild(img); }); function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let temp = array[i]; array[i] = array[j]; array[j] = temp; } }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Si la imagen debe repetirse, puede usar simple aleatorio como ese:

 const array = [1,2,3,4,5,6]; for(var i = 0; i < 4; i++){ console.log(array[Math.floor(Math.random() * 5)]); }

Como puede ver, el registro puede mostrarle la misma imagen (en mi ejemplo, solo un número).

about 4 years ago · Juan Pablo Isaza Report

0

 let array = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"]; const images = Array(4).fill(0).map(() => array[~~(Math.random() * array.length)]); console.log(images);

about 4 years ago · Juan Pablo Isaza Report

0

Puedes resolver esto usando un pequeño bucle.

 let images = ["../media/pawn.png", "../media/rook.png", "../media/knight.png", "../media/bishop.png", "../media/queen.png", "../media/king.png"]; function shuffleImages () { let temp = [] while (temp.length < 4) { temp.push(images[Math.floor((Math.random() * images.length - 1) + 1)]) } return temp; } let array = shuffleImages() console.log(array) array.forEach(function(image) { let img = document.createElement('img'); img.src = image; img.height = "45"; img.width = "50"; document.getElementById("random").appendChild(img); });
 <div id="random"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!