test
test

Reputation: 18198

jQuery - Working with arrays

OK so I fixed my last error with the DIV and all..

OK so at the very top of my javascript file... I have

$(function() {
     var games = new Array(); // games array
});

and then in a new function I have: var gamesLgth = games.length;

but when I run it, I get this: Uncaught ReferenceError: games is not defined

When I weird because I initalized it at the very beginning...

Upvotes: 0

Views: 886

Answers (2)

skyuzo
skyuzo

Reputation: 1138

games is out of scope. You need to store it somewhere such that your other function can access it.

For example, this will make your variable global.

var games;
$(function() {
    games = new Array(); // games array
});

$(function() {
   var gamesLgth = games.length;
   console.log(gamesLgth);
});

Upvotes: 0

Jamiec
Jamiec

Reputation: 136174

By declaring that variable within a function you have scoped the variable to that function, which means that that variable games is only available within that function.

$(function() {
     var games = new Array(); // games array

     ...


     var gamesLength = games.length; // works fine
});

But this following example will not:

$(function() {
     var games = new Array(); // games array
});

$(function() {
     var gamesLength = games.length; // won't work - im in a different scope
});

Upvotes: 0

Related Questions