Firebug is showing an error when I execute this code:
$.ajax({
type: "GET",
url: "../foos/.....",
dataType: "json",
success: function (foos, textStatus, XMLHttpRequest) {
for (var i = 0; i <= foos.length; i++) {
var foo = foos[i];
alert(foo.id);
};
}});
The json returns a var “foos” with id and name properties.
even alerting the foo.id propertie, firebug shows the error:
alert(foo.id) //foo is undefined
Why is foo undefined when it is correctly displayed in the alert?
EDIT:
I assigned foo twice, sorry. But even if I don’t do that, i have the same firebug error.
Which foo did you want? The foo from the array (foos) or the foo you re-declare within the loop:
But, crucially, this isn’t the problem. The problem is that you loop from
0tofoos.length:Which means on the last iteration of the loop, the index
iis 1 greater than the maximum index of the array. When you try to read this element it is, indeed, undefined.You should change your loop to:
(and of course get rid of the redefined
foo).Result should be: