gfppaste
gfppaste

Reputation: 1121

iterate through a common javascript collection?

So I have a common javascript collection, in this form:

function populateCollection(){
    var Collection = new Array();
    Collection['A'] = 'Awesome';
    Collection['B'] = 'Better';
    Collection['C'] = 'Cool';
    return Collection;
}

in a file (lets say it's called CommonLib.js).

Now say I'd like to keep this file as a common library, to be accessible by several different JS documents (Assume the library is very large).

What would be the best way to iterate through this collection from a document called, say jsDoc1.js?

I gave it a shot with:

<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function dropdown() { 
    for(var i in languageCollection){
        alert(i);
    }
}
<script>
<body>
<input type="text" name="example" id="color" onclick="dropdown()">
</body>

But I keep getting a languageCollection not defined error. I'm very new to jscript and jquery... any advice for me?

Thank you!

Upvotes: 0

Views: 131

Answers (1)

Sirko
Sirko

Reputation: 74086

You don't include the file with your collection. Insert the following statement:

 <script src="/path/to/CommonLib.js"></script>

Furthermore, you are only defining a function, which returns your collection and no global object for that. So you first have to call that function, e.g.,

var myCol = populateCollection();

then you can access it like the following:

for ( var i in myCol ) {
  if( myCol.hasOwnProperty( i ) {
    // do your stuff
    alert( i );
  }
}

Alternativly you can change your function to use a global variable, which would be visible to every scope.

function populateCollection(){
    window.myNamespace = window.myNamespace  || {};
    window.myNamespace.Collection = {};
    window.myNamespace.Collection['A'] = 'Awesome';
    window.myNamespace.Collection['B'] = 'Better';
    window.myNamespace.Collection['C'] = 'Cool';
}

By the way your are using an array as if it was an object. If there are no other aspects to justify that, change your function to the following:

function populateCollection(){
    return {
      'A': 'Awesome',
      'B': 'Better';
      'C': 'Cool'
    };
}

Upvotes: 4

Related Questions