2014-10-11 72 views
0

這裏遇到了一個小問題。 我想創建一個函數,顯示多個對象的內容。 因此,我創建了下面的代碼和它的作品,但由於某種原因它停止的第一對象之後,我只是爲什麼發生這種情況沒有得到它:/顯示多個對象的內容?

var space = '-'; 

function showObjects() { 

    for (indexArgument = 0; indexArgument < arguments.length; indexArgument++) { 

     for (indexObject in arguments[indexArgument]) { 

      console.log(space + indexObject + ' : ' + arguments[indexArgument][indexObject]); 

      if (typeof arguments[indexArgument][indexObject] === 'object') { 

       space += '-'; 
       showObjects(arguments[indexArgument][indexObject]); 

      } 

     } 

    } 

} 

var object1 = { a : 1, b : 2 , data : { a : 12 } }; 
var object2 = { a : 6, b : 9 , data : { a : 17 } }; 

showObjects(object1, object2); 

回答

1

的問題是,所有變量是全球
要使indexArgumentindexObject本地很容易(在它們前面添加一個var) - 但要使代碼與space變量一起工作,必須稍微重構代碼。

我會建議分裂「論據」和「遞歸」的邏輯,像這樣:

function showObjects() { 

    // loop through all arguments and call the recursive function 
    for (var indexArgument = 0; indexArgument < arguments.length; indexArgument++) { 
     // call the recursive function (with a additional space parameter) 
     showObject(arguments[indexArgument], '-'); 
    } 

    // the recursive function 
    // (handles only one object, with the local space variable) 
    function showObject(object, space) { 
     for (var indexObject in object) { 
      console.log(space + indexObject + ' : ' + object[indexObject]); 
      if (typeof object[indexObject] === 'object') { 
       // recursive call of this function 
       showObject(object[indexObject], space + '-'); 
      } 
     } 
    } 

} 

var object1 = { a : 1, b : 2 , data : { a : 12 } }; 
var object2 = { a : 6, b : 9 , data : { a : 17 } }; 

showObjects(object1, object2); 
+0

大,正是我一直在尋找!馬丁恩斯特,謝謝你:) – Scdev 2014-10-11 13:03:42

1

讓你的變量indexArgumentindexObject地方像所以:

for(var indexArgument = 0; indexArgument < arguments.length; indexArgument++) { 

    for (var indexObject in arguments[indexArgument]) { 

     /* your code */ 

    } 
}