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

192
Views
¿Cómo puedo crear un aleatorizador de elementos de lista pero solo mostrar el elemento una vez?

Estoy buscando hacer un elemento aleatorio de lista que solo muestre ese elemento una vez. Tengo un aleatorizador básico que extrae de una matriz, pero cuando hago clic en el botón, simplemente continúa recorriendo cada elemento. ¿Hay alguna manera de hacer que cada elemento solo se muestre una vez y luego se detenga y/o muestre algo como "list over" una vez que se complete? Mis habilidades js son muy básicas...

El código del aleatorizador js:

 var techniques = [ "item 1", "item 2", "item 3", "item 4", "item 5" ] function newTechnique() { var randomNumber = Math.floor(Math.random() * (techniques.length)); document.getElementById('techDisplay').innerHTML = techniques[randomNumber]; }

y el html

 <div id="techDisplay"></div> <button onclick="newTechnique()">New Technique</button>

También me pregunto si hay una mejor manera de obtener datos, como usar un xml o algo así. Tengo la intención de tener probablemente más de 50 elementos en la lista, lo que podría volverse engorroso en js. ¡Déjame saber, y gracias por adelantado!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Simplemente baraje la matriz primero. Esto se llama la 'reproducción aleatoria de Durstenfeld'.

Para responder si debe obtener los datos a través de XML o en algún otro lugar, diría que quizás considere simplemente crear un archivo JSON. Absolutamente no tendrá problemas de rendimiento hasta que obtenga cientos de miles de registros, así que ni siquiera se preocupe por el rendimiento si está trabajando con una cantidad de datos tan pequeña. Personalmente, normalmente mantengo un archivo separado que contiene funciones que devuelven todos los datos iniciales que necesito, o simplemente puede crear un archivo JSON e importarlo tan pronto como abra su aplicación.

¿Cómo aleatorizar (barajar) una matriz de JavaScript?

 let techniques = [ "item 1", "item 2", "item 3", "item 4", "item 5" ]; let techniquesRandom = shuffleArray(techniques); console.log(techniquesRandom); function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; }

about 4 years ago · Juan Pablo Isaza Report

0

si te entendí, quieres decir que quieres aleatorizar los elementos de la matriz: este es el código

 function shuffle(array) { randoms = [Math.trunc(Math.random() * array.length)]; let length = array.length; while (randoms.length != length) { for (let i = 0; i < array.length; i++) { r = Math.trunc(Math.random() * array.length); if (!randoms.includes(r)) { randoms.push(r); } } } let result = []; for (let b = 0; b < array.length; b++) { result.push(array[randoms[b]]); } return result; }

about 4 years ago · Juan Pablo Isaza Report

0

Aquí está el código para la funcionalidad que está buscando.

 const techniques = [ 'Currently showing item 1', 'Currently showing item 2', 'Currently showing item 3', 'Currently showing item 4', 'Currently showing item 5', 'Currently showing item 6' ]; let flags = techniques.map(() => false); function getNotShownNumber() { let whichItemToShow; const allAreTrue = flags.every((v) => v === true); if (!allAreTrue) { let value = true; do { const randomNumber = Math.floor(Math.random() * techniques.length); const alreadyShown = flags[randomNumber]; if (!alreadyShown) { flags[randomNumber] = true; whichItemToShow = randomNumber; value = false; } } while (value); } else { whichItemToShow = 'Completed'; } return whichItemToShow; } function newTechnique() { const number = getNotShownNumber(); const content = number === 'Completed' ? 'List Over' : techniques[number]; document.getElementById('techDisplay').innerHTML = content; }
 <div id="techDisplay"></div> <button onclick="newTechnique()">New Technique</button>

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!