¡Hola, comunidad de StackOverflow! Mi nombre es Piet.
Mientras investigaba el amado Javascript me quedé un poco atascado:
No estoy seguro de por qué recibo 98 elementos vacíos en mi matriz.
En Index[0] e Index[99] obtengo IntegerValues como se esperaba.
¡Gracias por sus respuestas! :)
// create an Array with the size of N(x) and // fill it with numbers in a range from 0 to 100 randomly. createNSizedArray = (x) => { for(let i = 0; i < x; i++) { var arr = []; arr[i] = arr.push(Math.round(Math.random()*100)); } return arr; } console.log(createNSizedArray(100)); // output -> [ 31, <98 empty items>, 1 ]; // Why are the other 98 items in the Array empty and how to change them into integer values?
En realidad, inspeccioné los artículos [1-98] para averiguar sus valores y verificar si realmente están vacíos.
Pero:
console.log(arr[4]) por ejemplo, devuélveme "indefinido". Así que no están realmente vacíos.
Está obteniendo una matriz en su mayoría indefinida porque está definiendo una nueva variable arr
en cada iteración. Debe mover la declaración de arr
fuera del bucle.
Aquí hay una alternativa rápida: Array(100).fill().map(_=>Math.round(Math.random()*100))
Intente mover la inicialización de la matriz antes del bucle for. Esto asegura que no cree una nueva matriz cada vez que se ejecuta el bucle.
Es porque está creando una nueva matriz en cada iteración. Prueba esto:
createNSizedArray = (x) => { var arr = []; for (let i = 0; i < x; i++) { arr[i] = arr.push(Math.round(Math.random() * 100)); } return arr; };