• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

62
Views
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 1 month ago ·

Juan Pablo Isaza

3 answers
Answer question

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 1 month ago · Juan Pablo Isaza Report

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 1 month ago · Juan Pablo Isaza Report

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 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.