Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

393
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda