Javascript 基于嵌套 for 循环以及对象

Javascript based nested for loop along with Objects

我是 javascript 的新手。当我使用对象和嵌套循环时。 plunker 可用

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

我收到类似 TypeError: Cannot set property 'c' of undefined 的错误,有人可以解释一下为什么它会这样工作吗?我一直在寻找这样的东西

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

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

因为数组 ab 的大小是 1 并且当你的 y 变成 1 试图访问数组 b 中的第二项时,它将 return 未定义(因为那个值不存在)。

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

TypeError: Cannot set property 'c' of undefined

因为在它抛出此错误时,y 大于 0,但您的 b 数组中只有 1 个元素。

我假设您在控制台中看到:

[object Object]

[object Object]

[object Object]

然后然后错误。这表明内部 for 循环处于第二次迭代中。

在您的错误发生时,您可以将代码解释为:

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

您可以尝试这样的操作:

Array.forEachfor..in

的组合

var a = [{b:[{c:"Test"}]}]

// a is Array. Use Array.forEach
a.forEach(function(item){
  
  // Check if current element is Object. If yes, use for..in
  if(typeof(item) === "object"){
    for(k in item){
      
      // Check if current item is Array and again loop over it
      if(Array.isArray(item[k])){
        item[k].forEach(function(o){
          
          // Print necessary value.
          console.log(o.c);
        })
      }
    }
  }
});

因为你要迭代它 10 次,它应该迭代与数组长度相同的次数,所以在第一个循环中使用 a.length,在第二个循环中使用 a[x].b.length

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