Search code examples
javascriptobjectfor-loopnested-loops

Javascript based nested for loop along with Objects


I'm new to javascript. when I was working with objects and nested loop. plunker is available

var a = [{b:[{c:null}]}]
for(var x= 0 ; x<10;x++){
  for(var y= 0 ; y<10;y++){
    console.log(a);
    a[x].b[y].c = y;
    console.log(a);
  }
}

I was getting error like TypeError: Cannot set property 'c' of undefined can some one please explain why it is working like this. I was looking to have like this

a[0].b[0].c = 1;
a[0].b[1].c = 2;......
a[1].b[0].c = 1;....
a[9].b[9].c = 9;

Solution

  • I was getting error like TypeError: Cannot set property 'c' of undefined can some one please explain why it is working like this

    Because size of array a and b is 1 and moment your y becomes 1 which tries to access 2nd item in array b, it will return undefined (since that value doesn't exists).

    so b[1].c -> undefined.c -> error (below)

    TypeError: Cannot set property 'c' of undefined