Javascript cannot set property 0 from undefined
This code generates an error:
Uncaught TypeError: Unable to set property '0' from undefined
Although I want to assign random numbers in an array, please help.
var array;
for (var i = 1; i < 10; i++) {
array[i] = Math.floor(Math.random() * 7);
}
console.log(array);
source to share
You are missing the array initialization:
var array = [];
Taking this as your example, you would:
var array = []; //<-- initialization here
for(var i = 1; i<10;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
Also you should start assigning values ββfrom the index 0
. As you can see in the log, all unassigned values ββget undefined
assigned to your index 0
.
So, the best solution would be to start with 0
and adjust the end for
to <9
so that it produces the same number of elements:
var array = [];
for(var i = 0; i<9;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
source to share