0

This is driving me absolutely nuts being a beginner JavaScript meddler.

I have an array called arrayA with the following data (in my actual code I declare arrayA with [] and then use $.getJSON to ingest a file that contains data):

 arrayA = [
    {
        "Key":  "Key1",
        "Value":  {
                      "info1":  "298431",
                      "info2":  "55.035",
                      "info3":  "11.375",
                  },
        "Name":  "Key1"
    }
]

In my HTML page, I have a script tag/section and this is defined there. After arrayA, I have a function called funcA() where I try and do "stuff" This includes things like finding the index for "Key1" as an example.

When doing console.log in line it always reports as 0 but when checking the length using Chrome's console it reports the correct number of objects (8950).

Not really sure what is the problem. Potentially variable scoping or the way the arrayA is initialised and loaded with data? Could someone help?

For completeness:

<script type="text/javascript">
var arrayA = [];

$.getJSON('./source.json', function(data) {
    arrayA = data;                  
});

function funcA() {
    //Do stuff to find indexOf "Key1"
}
</script>

/D

Daenous
  • 45
  • 1
  • 6
  • 1
    where are the logging statements? This will probably help [How to return the response of an asynchronous call](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – charlietfl Jan 08 '17 at 19:17
  • 3
    How do you use / invoke `funcA()` ? Why not showing that part of code? – Roko C. Buljan Jan 08 '17 at 19:19
  • Hi guys, thanks for the quick responses on all the possibilities. I shall try and reply in turn and update the question with more information as per some of the requests. Thanks! – Daenous Jan 08 '17 at 19:24

2 Answers2

2

The problem is most likely that when funcA() runs, the data is not yet available.

Try this:

<script type="text/javascript">
var arrayA = [];

$.getJSON('./source.json', function(data) {
    arrayA = data;                  
    console.log('Data was loaded', arrayA);
});

function funcA() {
    //Do stuff to find indexOf "Key1"
    console.log('funcA() ran');
}
</script>

Then you'll see in which order things happen. Of course $.getJSON being an async function, you can't rely things always happening in the same order. Therefore you should look into promises or callbacks, and not use global variables.

Schlaus
  • 18,144
  • 10
  • 36
  • 64
1

You are assigning data to arrayA asynchronously - when you are first inspecting the callback function for getJSON has not yet completed. If you would like to operate on the data you could call funcA inside the callback:

$.getJSON('./source.json', function(data) {
  arrayA = data;
  funcA();                 
});
hackerrdave
  • 6,486
  • 1
  • 25
  • 29