Im having some issues creating an array of objects in javascript
Please see my code below and tell me where im going wrong..
I simply want to loop through and access the values
<!-- 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>
The
for .. in ..works different in javascript than in some other languages. Instead of the object, you will get the key. In your array therefore you’ll get the index.For iterating over arrays, just use an index-based array to avoid hassle:
If you really want to use the
for .. in ..syntax, use this: