0

beginner trying to wrap my head around javascript and a scope issue im having.

Im pulling some json data and pushing it into an array called zero[] .. Getting it to work outside the anonymous function has failed.

What can i do to get zero[] to work outside the function?

<script>


 var addr = "data657";


 var zero = [];
 var full = [];

$(function(){


jQuery.getJSON('https://jsondataurl.com/'+addr, function(result) {


    if (result == 0)
     zero.push(addr);
if (result > 0)
     full.push(addr); 

var j = Math.floor(Math.random()*4); 



     alert(zero[j]);    /// works great here  !!!
});
});


alert(zero[j]); // DOES NOT work here



  $("#foo").attr("data-stuff", zero[j]);  // DOES NOT work here 


 </script>    
  • Hey its outside and not inside any function you can't use like zero[j] rather try zero[1] means you have to pass the reference number alert(zero[0]); will work you just passing only variable not a reference – Anto king Jul 18 '14 at 08:26
  • @Quentin the question here is different. This question is not about Ajax call. This is not a duplicate question. – vivek_ganesan Jul 18 '14 at 08:31
  • @vivek_ganesan — Yes, it is - `getJSON` makes an Ajax call. (There's a secondary problem in that `j` is out of scope, but it will go away when the code is rewritten to account for being asynchronous because that scope won't be used any more). – Quentin Jul 18 '14 at 08:32
  • @Quentin.. but the point of the question is not about Ajax call. The error in the code is about variable scope. – vivek_ganesan Jul 18 '14 at 08:33
  • No, look at the question "What can i do to get zero[] to work outside the function?" — there are no scoping issues with accessing `zero`, just timing ones caused by Ajax. – Quentin Jul 18 '14 at 08:38
  • argh.. how depressing. Just when i thought i was making some progress.. Thanks for the input Quentin. Ill look at the page you linked to and look for examples. – Fazeum Lifern Jul 18 '14 at 09:10

1 Answers1

0

zero is within scope. The variable just hasn't been populated yet. j happens to not be in scope.

Anything you want to do with data from a callback must be done within the callback.

Scimonster
  • 32,893
  • 9
  • 77
  • 89