2011-10-07 36 views
0

林有一些問題,在JavaScript中創建對象的數組JavaScript數組 - 如何循環並獲得對象值

請在下面看我的代碼,並告訴我在哪裏,我去錯了..

我只是想遍歷並訪問值

<!-- Read XML Script --> 
<script type="text/javascript"> 

    // Object array 
    var myArray = []; 

    $(document).ready(function() { 
     $.ajax({ 
      type: "GET", 
      url: "HighScore.xml", 
      dataType: "xml", 
      success: function (xml) { 
       $(xml).find('challenger').each(function() { 

        var name = $(this).find('Name').text(); 
        var watts = $(this).find('Watts').text(); 
        var Mins = $(this).find('Mins').text(); 

        // objects in the array 
        challenger = new Object(); 
        challenger.name = name; 
        challenger.watts = watts; 
        challenger.Mins = Mins; 

        myArray.push(challenger); 

       }); 

       // look into the array 
       for (obj in myArray) { 
        // do i need to cast ?? how can i view the object ?? 
        alert(obj + " - "); 
       } 


      }, 
      error: function() { 
       alert("error"); 
      } 
     }); 
    }); 

</script> 
+0

什麼你的意思是「查看對象」?你的意思是你怎麼能用它的屬性來執行'alert'? –

+0

是的,訪問它的屬性:) – JGilmartin

回答

1

for .. in ..工作在JavaScript比其他語言不同。而不是對象,你會得到鑰匙。在你的數組中,因此你會得到索引。

用於遍歷數組,只需使用一個基於索引的陣列,以避免麻煩:

for (var ix = 0; ix < myArray.length; ix++) { 
    var obj = myArray[ix]; 

    alert(obj.name); 
} 

如果你真的想使用for .. in ..語法,使用:

var a = ['jan', 'klaas']; 
for(var key in a) { 
    if (a.hasOwnProperty(key)) { 
     console.log(a[key].name); 
    } 
} 
1
-    for (obj in myArray) { 
-     // do i need to cast ?? how can i view the object ?? 
-     alert(obj + " - "); 
-    } 

+    for (var i = 0; i < myArray.length; i++) { 
+     var obj = myArray[i]; 
+     // do i need to cast ?? how can i view the object ?? 
+     alert(JSON.stringify(obj, null, ' ')); 
+    } 
相關問題