This code generates error:
Uncaught TypeError: Cannot set property '0' of undefined
While I want to assign random numbers in array, please help.
var array;
for (var i = 1; i < 10; i++) {
array[i] = Math.floor(Math.random() * 7);
}
console.log(array);
You are missing the array initialization:
var array = [];
Taking this into your example, you would have:
var array = []; //<-- initialization here
for(var i = 1; i<10;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
Also you should starting assigning values from index 0
. As you can see in the log all unassigned values get undefined
, which applies to your index 0
.
So a better solution would be to start at 0
, and adjust the end of for
to <9
, so that it creates the same number of elements:
var array = [];
for(var i = 0; i<9;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
You haven't told that array
is an array Tell to javascript that treat that as an array,
var array = [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With