Problem with array loop - Javascript

Asked

Viewed 101 times

-2

When I try to run the loop, even if I want to enter the is, I already checked and the array with the object is not empty, but does not execute the loop... Any idea?

var caminho = [];

$.get("http://localhost/crocs/arquivo.json", function(data) {

    data = typeof data == 'string' ? JSON.parse(data) : data;

    data.forEach(function(elementoDaArray) {

        skuid = elementoDaArray.SkuId;
        valor = elementoDaArray.Valor;
        letra = elementoDaArray.Letra;
        imagem = elementoDaArray.Imagem;

        caminho.push({
            img: imagem,
            id: skuid
        })
    });
});


for (var i = 0; i < caminho.length; i++) {
    console.log(products[i].img);
}
  • can put an example of the value of data?

  • {"Skuid":"331","Value":"9.90","Letter":"A","Image":"10006994_001UNI"} this is the json that returns through $.get

  • Luiz he is a simple object not an array, so the forEach won’t work

  • Try, before the forEach run this for you to see: skuid = data.SkuId;

1 answer

0

$.get is an asynchronous function, it takes a while to get the answer from your address, but the code does not wait for the function to finish to continue running. In this case, you are calling $.get, and then trying to read the array before you even fill it, if you want to continue with your code only after receiving the $.get response, put your loop inside the function. Other alternatives are working with callbacks or Promises.

  • Andre you are mistaken, he is treating the return within the function of callback which is the second parameter of get, that is, when it returns success, see the documentation if you have any doubt: https://api.jquery.com/jquery.get/

  • Yes, the return is handled within the callback function, but the loop (for, not the foreach) is outside the function, i.e.. 1-$.get is called. 2-the loop for runs. 3-the callback of $.get runs. In that order.

  • @Ricardopunctual what Andre wrote is correct, where do you think he’s wrong?

  • Hello, I read it now and I saw it calmly it’s really right, because @Andre is referring to for that is outside the callback, had understood that it was referring to the other loop, which by the way according to the example json will not work as it is not an array, my apologies :)

Browser other questions tagged

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