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.
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>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); // NaNEn 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.
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.