-1

I have this code. I need to see in the array y the objects assigned inside the for statement (increase and decrease). In the first console.log I can see the array updated but in the second it's empty.

function myfunction() {
var y = new Array(2);
    $.getJSON('../docs/natures.json', function(data) {
        var nature = document.getElementById("nature").value;
        for( var i = 0; i< data.natures.length; i++)
        {
            var x = data.natures[i];
            if((nature.localeCompare(x.name)) == 0)
            {
                y=[x.increase];
                console.log(y[0]);
                y.push(x.decrease);
                console.log(y[1]);
                break;
            }
        }   
        console.log(y);  <!- first ->
    });
console.log(y);  <!- second ->
}

my JSON file is like this :

{"natures":[
{
"name":"some name",
"increase": "some increase",
"decrease": "some decrease"
},
{...}
]}

My results in the console

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Aug 17 '17 at 23:12

1 Answers1

1

jQuery.getJSON is Asynchronous, the callback function passed to it will only be run when the request is complete.

console.log(y);  <!- second -> 

occurs prior to that

andrew
  • 9,313
  • 7
  • 30
  • 61