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);
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);
Share
Improve this question
edited Jul 29, 2019 at 5:26
Nick Parsons
50.7k6 gold badges57 silver badges75 bronze badges
asked Jun 14, 2017 at 9:12
aashir khanaashir khan
5383 gold badges9 silver badges24 bronze badges
5
|
3 Answers
Reset to default 17You 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 = [];
you need to initialize the array first
var array = [];
after adding this line your code should work properly
array
as an arrayvar array=[];
and to avoid getting undefined forarray[0]
I would recommend you change your loopvar i = 0; i<9;i++
or maybe usearray.push();
– NewToJS Commented Jun 14, 2017 at 9:16