I am attempting to extract information from a JSON file with the following data: [3000,2500,6000,2200,5000,1300]. The file is named data.txt. To achieve this, I initialize an empty array in my code. Subsequently, I utilize the $.getJSON function by passing a function that reads the contents of the data.txt file. I iterate through each item in the JSON array and append it to the previously created empty array. However, when I attempt to display the first element of the array using arr[0], I receive an 'undefined' message. Interestingly, if I place the document.write(arr[0]); line before the closing bracket, it returns the correct value of 3000. Nevertheless, I require this to function outside of the current position. What could be causing this discrepancy?
arr=[];
$.getJSON('data.txt',function(data) {
for (var i in data){
arr.push(data[i]);
}
});
document.write(arr[0]);