0

I created the array in the scope of $(document).ready(function(){});

for example:

$(document).ready(function(){
    $.getJSON("data.json", function(json) {

        function Question(q,correactA,array)
        {
            this.question=q;
            this.correct_a=correactA;
            this.answers=array;

        }

        multiQ= new Array();
        for (i=0;i<5;i++)
        {
            var q = json.questions[i].question;
            var corA= json.questions[i].correct_answer;
            var a = json.questions[i].answers;
            var aString = "";
            Object.keys(a).forEach(function (k) {aString += a[k] ;})
            multiQ[i]=new Question(q,corA,aString);
        }

        for (i=0;i<5;i++)
        {
            console.log(multiQ[i]);
        }

    });
});

Now I want to send the multiQ array to external var outside the scope. How can I do it?

Suganth G
  • 5,136
  • 3
  • 25
  • 44
Sara
  • 53
  • 8
  • 1
    *I created the array in the scope of* — No, you didn't. There is no `var` statement. It's a global already. – Quentin Aug 09 '14 at 11:42
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/1048572) – Bergi Aug 09 '14 at 11:49

2 Answers2

-1

It's very ugly, but you could assign a global getter inside the document.ready. For example:

var multiQ = new Array();
window.getMultiQ = function() { return multiQ; }

Then outside of document ready, you could call "var q = getMultiQ();"

Again, this is very ugly and would lead to unmaintainable code very fast. Most likely, there's an easier/cleaner way to accomplish what you're trying to do.

joeltine
  • 1,610
  • 17
  • 23
-1

Declare

var multiQ= new Array();

outside $(document).ready function:

var multiQ= new Array();
$(document).ready(function(){
    $.getJSON("data.json", function(json) {

        function Question(q,correactA,array)
        {
            this.question=q;
            this.correct_a=correactA;
            this.answers=array;

        }

        for (i=0;i<5;i++)
        {
            var q = json.questions[i].question;
            var corA= json.questions[i].correct_answer;
            var a = json.questions[i].answers;
            var aString = "";
            Object.keys(a).forEach(function (k) {aString += a[k] ;})
            multiQ[i]=new Question(q,corA,aString);
        }

        for (i=0;i<5;i++)
        {
            console.log(multiQ[i]);
        }

      });
});
jimm101
  • 948
  • 1
  • 14
  • 36
  • Yes, there's an asynchronous call, so each multiQ[i] won't be populated immediately. In the OP's code, it would be undefined until the callback, in the modification, it would be defined and have 0 length. – jimm101 Aug 11 '14 at 12:43