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);
      

Run codeHide result


+4


source to share


3 answers


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);
      

Run codeHide result




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);
      

Run codeHide result


+7


source


You didn't say it array

is a Tell to javascript array treating it as an array,



var array = [];

      

+2


source


you need to initialize the array first

 var array = [];

      

after adding this line your code should work correctly

0


source







All Articles