2016-03-14 36 views
-3

我是javascript的新手。當我使用對象和嵌套循環時。 plunkerJavascript基於嵌套for循環與對象

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; 
+0

你想做些什麼?你的預期產出是多少? – C2486

+0

'a [9] .b [9] .c = 9;'因爲var a = [{b:[{c:null}}}]''不能工作' –

+0

如果我需要,我該如何實現? ? – santhosh

回答

5

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中,它會返回undefined(因爲該值不存在)。

所以b[1].c - >undefined.c - >錯誤(下面)

TypeError: Cannot set property 'c' of undefined

+0

沒關係,但它仍然令我困惑.... – santhosh

+0

atleast你能提供我的博客或東西,這樣我就可以理解 – santhosh

+0

@santhosh看看這個文件在循環和迭代https:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration你能特別提一下你到底在搞什麼嗎? – gurvinder372

2

因爲在該點它將引發此錯誤,y是大於0,但是隻有1在b數組元素。

我要去承擔,在控制檯,你會看到:

[object Object]

[object Object]

[object Object]

而且然後錯誤。這將表明內循環處於第二次迭代中。

在發生的錯誤的時候,你可以解釋的代碼爲:

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

你可以嘗試這樣的事情:

組合的 Array.forEach

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

+0

@Downvoter,請分享答案中缺少的內容。謝謝 – Rajesh

1

因爲您迭代了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); 
 
    } 
 
}