Thiago
Thiago

Reputation: 1555

Why is this object undefined?

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.

Upvotes: 0

Views: 131

Answers (1)

Jamiec
Jamiec

Reputation: 136104

Which foo did you want? The foo from the array (foos) or the foo you re-declare within the loop:

for (var i = 0; i <= foos.length; i++) {
    var foo = {
        id: "",
        name:""
    };

    var foo = foos[i];
    alert(foo.id);
 };

But, crucially, this isn't the problem. The problem is that you loop from 0 to foos.length:

for (var i = 0; i <= foos.length; i++)

Which means on the last iteration of the loop, the index i is 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:

for (var i = 0; i < foos.length; i++)

(and of course get rid of the redefined foo).

Result should be:

for (var i = 0; i < foos.length; i++) {
    var foo = foos[i];
    alert(foo.id);
 };

Upvotes: 5

Related Questions