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!
You don’t include the file with your collection. Insert the following statement:
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.,
then you can access it like the following:
Alternativly you can change your function to use a global variable, which would be visible to every scope.
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: