Javascript cannot set property 0 of undefined
You haven't told that array
is an array Tell to javascript that treat that as an array,
var 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);