jquery array constants
- how do i create a jquery constants file and access it from other js files?
- how do i do this?
I have a list of strings. I need to put them into an array A1. Then i need to create another array A2 for some of the elements in A1. The values for A2 would be elements from A1. It's sort of like grouping the strings in A1 to form A2, but i need access to A1 and A2. What's the best way of doing this with javascript/jquery? I figured if I put them into constants, I wouldn't have to repeat them, should the element values change.
e.g.
A1 = "a", "cat", "hat","b", "bob", "ben", "c", "c开发者_运维百科lay", "course", "d", "e", "done"
A2["a"] = "cat", "hat"
A2["b"] = "bob", "ben"
A2["c"] = "clay", "course"
if "cat" becomes "cot", i don't want to have to change it in multiple places... what's the least messy way to do this and make these arrays available to other js files?
Then just create .js file called constants.js
with the following in it:
var A1 = ["a", "cat", "hat","b", "bob", "ben", "c", "clay", "course", "d", "e", "done"];
var A2["a"] = ["cat", "hat"];
var A2["b"] = ["bob", "ben"];
var A2["c"] = ["clay", "course"];
And reference it in your pages' HTML before any other script (.js file):
<script type="text/javascript" src="constants.js"><script/>
That way, all of your scripts will have access to the variables in constants.js
, and you can go and modify constants.js
whenever you want to change those variables.
To answer your first question, this kind of reminds me of enumerated types. The way I would handle your constants would be as such...
var constants = {
a : "a",
cat : "cat",
hat : "hat",
bob : "bob",
clay : "clay"
};
... and you can access these by constants.bob
, constants.clay
, etc... after you include the JavaScript file into your page as is done traditionally:
<script type="text/javascript" src="path-to-js-file/constants.js"></script>
As far as your second question, this reminds me of a Hash Table. I'll think about the problem and come back in a bit.
I hope this helps.
To access your constants from another file, a handy jQuery method is 'getScript'. Use the same relative path that you would if accessing the file from your html/jsp/etc files (i.e. the path is NOT relative to where you place the getScript method, but instead relative to your domain path). For example, for app at localhost:8080/myDomain:
$(document).ready(function() {
$.getScript('/myDomain/myScriptsDir/constants.js');
...
then, if you have this in a file called constants.js:
var jsEnum = { //not really an enum, just an object that serves a similar purpose
FOO : "foofoo",
BAR : "barbar",
}
You can now print out 'foofoo' with
jsEnum.FOO
We can create a constant just like below. It work like a static class
function Helper() { }
Helper.LocationType = {
Division: "Division",
Region: "Region",
Unit: "Unit",
HeadOffice: "HeadOffice",
HO: "HO"
};
We can now access just type Helper.LocationType.Division
return Division, Helper.LocationType.Region
return Region
精彩评论