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

298
Views
¿Establecer un rango de inicio y final personalizado en una matriz que muestra una cadena aleatoria?

Estoy jugando con JavaScript mientras me preparo para mi entrevista con un desarrollador junior.

Estoy tratando de escribir una función que acepte dos parámetros, un punto inicial y un punto final , en una matriz. Esta función debería generar un nombre aleatorio dentro de un punto inicial y final personalizado de la matriz. Parecía estar cerca de hacerlo bien, pero muestra NaN . ¿Qué es NaN ?

Aquí está el código que escribí.

 const names = ['Kitana', 'Liu Kang', 'Sonya Blade', 'Johnny Cage', 'Jax Briggs', 'Smoke', 'Sheeva', 'Jade'] const section = document.querySelector('section') const para = document.createElement('p'); // Add your code here function random(beginIndex, endIndex) { for (let beginIndex = 0; beginIndex < names.length; beginIndex = beginIndex + endIndex) { let newRangeOfIndices = names[beginIndex] const randomName = Math.floor(Math.random() * newRangeOfIndices) para.textContent = randomName } } random(2, 5) // Don't edit the code below here! section.innerHTML = ' '; section.appendChild(para);
 <section></section>

Notará que ya establecí un límite personalizado en la función que se ejecutará, de 2 a 5. Pero aún no funciona. Por favor, ayúdame.

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

0

No necesita for loop para obtener un número aleatorio.

Para obtener un índice aleatorio.

 let randomIndex = Math.floor(Math.random() * (endIndex - beginIndex + 1) + beginIndex)

Luego obtenga el nombre aleatorio de la matriz de names .

 let randomName = names[randomIndex] 

 const names = ['Kitana', 'Liu Kang', 'Sonya Blade', 'Johnny Cage', 'Jax Briggs', 'Smoke', 'Sheeva', 'Jade'] const section = document.querySelector('section') const para = document.createElement('p'); // Add your code here function random(beginIndex, endIndex) { let randomIndex = Math.floor(Math.random() * (endIndex - beginIndex + 1) + beginIndex) let randomName = names[randomIndex] para.textContent = randomName } random(2, 5) // Don't edit the code below here! section.innerHTML = ' '; section.appendChild(para);
 <section></section>

about 4 years ago · Juan Pablo Isaza Report

0

El autor hizo dos preguntas aquí... la primera relacionada con el código y aquí está mi solución:

 const names = ['Kitana', 'Liu Kang', 'Sonya Blade', 'Johnny Cage', 'Jax Briggs', 'Smoke', 'Sheeva', 'Jade']; // create a generic randomName function that takes 3 parameters beginIndex, endIndex and an array which returns a random positioned value within the range function randomName(beginIndex, endIndex, arr) { const randomNumber = Math.floor(Math.random() * (endIndex - beginIndex + 1) + beginIndex); return arr[randomNumber]; } // call the function with the proper argument randomName(2, 5, names);

la segunda pregunta es ¿Qué es NaN ?

Respuesta: según lo establecido por MDN Docs

La propiedad global NaN es un valor que representa Not-A-Number.

Al calcular números pero enviar un valor de cadena para analizar, el analizador de JavaScript arroja un error que indica que no es Not-A-Number .

a ver tenemos dos variables

 let x = 10; let y = 'hello'; console.log(typeof x); // number console.log(typeof y); // string // try to multiplied x by y console.log(x * y); // NaN

En tu caso:

 function random(beginIndex, endIndex) { for (let beginIndex = 0; beginIndex < names.length; beginIndex = beginIndex + endIndex) { // this will be a string that extracts the value of the beginIndex position value from the names array. let newRangeOfIndices = names[beginIndex] // here you try to multiply the Random Number by a string and getting NaN const randomName = Math.floor(Math.random() * newRangeOfIndices) para.textContent = randomName } } random(2, 5)

Los mejores deseos para su entrevista.

about 4 years ago · Juan Pablo Isaza Report

0

Usar:

 return Math.random() * (max - min) + min;

Para obtener un número como min-max. Luego, use la salida del número aleatorio como un índice en la matriz. Evite siempre los bucles for en situaciones como esta; lo más probable es que siempre haya otra forma de hacerlo.

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!