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.
CodePudding user response:
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))
CodePudding user response:
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.
CodePudding user response:
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;
};
CodePudding user response:
you could use the Array method.
const createNSizeArray = (n) => {
return Array.from({ length: n }, () => Math.round(Math.random()*100 );
};
console.log(createNSizeArray(5)) // [81, 92, 23, 54, 12]
CodePudding user response:
Possible solution:
const createNSizedArray = (x) => {
// it had to be moved outside the for-loop to prevent from setting everything so far to an empty array
let arr = [];
for (let i = 0; i < x; i ) {
// here you don't need both arr.push(...) and assignment
arr[i] = Math.round(Math.random()*100);
}
return arr;
}
console.log(createNSizedArray(100));
What Array.prototype.push
does:
let arr = [];
console.log(arr);
arr.push(1);
console.log(arr); // [1]
arr.push(2);
console.log(arr); // [1,2]
arr.push(3);
console.log(arr); // [1,2,3]
What you're trying to achieve, as @Vincent suggested, can easily be done with:
Array(100).fill().map(_ => Math.round(Math.random() * 100))