Fork Spoon
Fork Spoon

Reputation: 21

JavaScript Arrays and Scope

This must be very simple but I've been at this far too long and I just cannot find a relevant answer anywhere.

It's quite simple, really.

When my code is like this:

/* functionsAndStuff.js */
var x = [ [1,2], [3,4] ];
function doStuff(){
    var value = x[0][0];
    return value; //BROKEN
}

Nothing happens. This code here, on the other hand, works out just fine:

/* functionsAndStuff.js */
function doStuff(){
    var x = [ [1,2], [3,4] ];
    var value = x[0][0];
    return value; //returns 1
}

The doStuff() function returns the value to index.html, a different page. index.html uses the function to do it's own thing.

Changing it up and doing this makes it work:

/* index.html */
var x = [ [1,2], [3,4] ];


/* functionsAndStuff.js */
function doStuff(){
    var value = x[0][0];
    return value; //returns 1
}

I suppose if I just define the matrix in index.html, my problem will go away... but that's a bit of a sloppy solution.

I have another array which starts off empty. This array is then later populated by splitting a string. This array is completely accessible. But I still can't access the x array at all, which is being filled in manually (ie hard coded).

Upvotes: 1

Views: 187

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

The first function you have listed works fine, at least in FF16.

var x = [ [1,2], [3,4] ];
function doStuff(){
    var value = x[0][0];
    return value; //BROKEN
}

alert(doStuff()); //returns 1

Example: http://jsfiddle.net/UD8Zs/

Upvotes: 2

Related Questions