Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

390
Vistas
How to create an N_sized Array with the size of N(x) and fill it with the numbers in a range from 0 to 100 randomly?

Hello StackOverflowCommunity! My name is Piet.

While investigating the beloved Javascript I got a bit stuck:

I´m not sure why I get 98 empty items pushed into my Array.

On Index[0] and Index[99] I get IntegerValues as expected.

Thank you for your answers! :)

// 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?

Actually I inspected the Items[1-98] to find out their values and to check if they are really empty.

But:

console.log(arr[4]) for example return "undefined" to me. So they are not really empty.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are getting a mostly undefined array because you are defining a new variable arr at each iteration. You should move the declaration of arr outside of the loop.

Here is a quick alternative: Array(100).fill().map(_=>Math.round(Math.random()*100))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try moving the initialization of the array before the for loop. This makes sure that you don't make a new array every time the loop runs.

about 4 years ago · Juan Pablo Isaza Denunciar

0

It is because you are creating a new array on each iteration. Try this:

createNSizedArray = (x) => {
  var arr = [];
  for (let i = 0; i < x; i++) {
    arr[i] = arr.push(Math.round(Math.random() * 100));
  }
  return arr;
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda