Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript cannot set property 0 of undefined

Tags:

javascript

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);
like image 724
aashir khan Avatar asked Jun 14 '17 09:06

aashir khan


2 Answers

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);
like image 163
Isac Avatar answered Oct 23 '22 00:10

Isac


You haven't told that array is an array Tell to javascript that treat that as an array,

var array = [];
like image 41
Suresh Atta Avatar answered Oct 22 '22 23:10

Suresh Atta