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

186
Views
Elija texto aleatorio de una matriz

Lo he hecho, pero ¿es posible mostrarlo solo una vez y eliminarlo de la lista para cada cosa?

Por ejemplo, primero muestra el "primero" Cuando se envió, quiero enviar los otros 3 mensajes, y cuando está vacío, indica que no hay [respuestas] en la lista.

 const messages = ["first", "two", "three", "four"] const randomMessage = messages[Math.floor(Math.random() * messages.length) - 1];
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Sugeriría usar un algoritmo de barajado para barajar sus mensajes, luego puede usar Array.shift() para seleccionar mensajes uno por uno.

La función de shuffle() aquí es una reproducción aleatoria básica de Fisher-Yates / Knuth .

 function shuffle(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } const messages = ["first", "two", "three", "four"]; const randomizedMessages = shuffle(messages); let i = 0; // Take messages one by one using Array.pop() while(randomizedMessages.length) { console.log(`Message #${++i}:`, randomizedMessages.shift()); }
 .as-console-wrapper { max-height: 100% !important; top: 0; }

O usando lodash shuffle :

 const messages = ["first", "two", "three", "four"]; const randomizedMessages = _.shuffle(messages); let i = 0; while(randomizedMessages.length) { console.log(`Message #${++i}:`, randomizedMessages.shift()); }
 .as-console-wrapper { max-height: 100% !important; top: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>

about 4 years ago · Juan Pablo Isaza Report

0

Después de usarlo, puede encontrar el índice del elemento seleccionado y luego eliminarlo inmediatamente.

 const messages = ["first", "two", "three", "four"] const index = Math.floor(Math.random() * messages.length) const randomMessage = messages[index] messages.splice(index, 1) //rest of what you are going to do with 'randomMessage'

En cuanto a verificar si está vacío, simplemente verifique randomMessage messages.length Ambos serán falsos si la matriz está vacía ( messages.length será 0 y randomMessage no estará undefined )

 if (!messages.length) console.log("The array is empty!")
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!