2011-10-07 70 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, ' ')); 
+    } 
相关问题