Unable to read property

Asked

Viewed 341 times

1

I have a problem that seems simple, but I can’t find the solution.

table = "<div><table class='table table-hover'>";
dados = "";

for(var i = 0; i <= retorno.dados.length; i++)
{
    dados = dados + "<tr><td class='col-md-11'>" + retorno.dados[i]['user_id'] + "    </td>";         
    // console.log(retorno.dados[i]['user_id']);
}

The error in the console is as follows: Uncaught Typeerror: Cannot read Property 'user_id' of Undefined

  • What gives console.log(typeof retorno.dados, JSON.stringify(retorno.dados));?

  • On the console only appears :Uncaught Typeerror: Cannot read Property 'user_id' of Undefined.

  • But when I give an Alert(return.data[i]['user_id']), it shows the data correctly.

  • Put what I asked before of the line dados = dados + ...

  • Ok, on the console gave the following result; Object [{"user_id":"asdsad","user_admin":"0"},{"user_id":"dasdsadasdasdsad","user_admin":"0"},{"user_id":"dddddddddddddddd","user_admin":"1"},{"user_id":"dsfsdfsdfsdf","user_admin":"0"},{"user_id":"ewrewr","user_admin":"0"},{"user_id":"hgkhjkhjykhjkhj","user_admin":"0"},{"user_id":"jhgjhgjhgjhgj","user_admin":"0"},{"user_id":"oiupipoip","user_admin":"1"},

  • 1

    Moult i<= for i< in the for cycle...

  • 1

    Okay, now it worked, thank you very much

Show 2 more comments

1 answer

0


When you cycle through an array for(var i=0;i<= you have to stop before i be equal to the last element of the array.

Says so on MDN about .length:

The length Property [...] is Always numerically Greater than the Highest index in the array.

That is, the property length is always larger than the last element of the array, so it cannot be used <=.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.