我在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 :(得分: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 :(得分: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, ' '));
+ }