最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript cannot set property 0 of undefined - Stack Overflow

programmeradmin3浏览0评论

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 You haven't assigned "array" to anything, it is not currently an array object – Patrick Evans Commented Jun 14, 2017 at 9:13
  • Define array as an array var array=[]; and to avoid getting undefined for array[0] I would recommend you change your loop var i = 0; i<9;i++ or maybe use array.push(); – NewToJS Commented Jun 14, 2017 at 9:16
  • I follow your suggestion but still its not resolve. – aashir khan Commented Jun 14, 2017 at 9:24
  • @aashirkhan Maybe this will help. I have a working example of my suggestions. jsfiddle.net/zuzy01m2 – NewToJS Commented Jun 14, 2017 at 9:29
  • Possible duplicate of Uncaught TypeError: Cannot set property '0' of undefined " – ADH - THE TECHIE GUY Commented Jun 28, 2019 at 19:08
Add a comment  | 

3 Answers 3

Reset to default 17

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

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

发布评论

评论列表(0)

  1. 暂无评论