我是一个javascript新手,怀疑通过简单的例子解释得很好?
var hashAfrica = { "country" : new Array()};
// populate all countries in africa.
var arr = hashAfrica["country"];
arr.push("kenya");
arr.push("egypt");
var hashAsia = { "country" : new Array()};
// populate all capitals in asia.
var arr = hashAsia["country"];
arr.push("india");
arr.push("china");
var hashAmerica = { "country" : new Array()};
// populate all capitals in america.
var arr = hashAmerica["country"];
arr.push("usa");
arr.push("canada");
我想做的是:
var hash = { "country" : new Array()};
var hashAfica = new hash();
var hashAsia = new hash();
var hashAmerica = new hash();
如何在javascript中完成此操作?
答案 0 :(得分:3)
您可以使用
function hash() {
this.country = []; // or: new Array();
}
通过new hash()
创建此类对象。或者你只是做
function getCountryArray() {
return {country: []};
}
并像hashAfrica = getCountryArray()
一样使用它。
但请注意,您没有使用类似于哈希映射的任何内容。您并未将所有这些数组用作散列图,而是将其用作简单列表。如果你想在JavaScript中制作某种地图,只需使用动态添加键的对象。
您确定不想要
等结构吗?var countryHash = {
"africa": ["kenya", "egypt"],
"asia": ["india", "china"],
"amerika": ["usa", "canada"]
};
答案 1 :(得分:1)
如果您想使用new hash()
,那么您可以将hash()
定义为构造函数,并按以下方式执行:
function hash() {
this.country = [];
}
var hashAfrica = new hash();
hashAfrica.country.push("kenya");
hashAfrica.country.push("egypt");
// and so on...
var hashAsia = new hash();
var hashAmerica = new hash();
就个人而言,我不会将其称为hash
,因为它与哈希对象没有任何关系。您只是将一组国家/地区存储在一个对象中。我可能会称它为continentInfo
,并且还定义了一个可以填充初始国家/地区列表的构造函数:
function ContinentInfo(list) {
// if initial argument passed, then split it into an array
// and set initial country array from it
if (list) {
this.countries = list.split(" ");
} else {
this.countries = [];
}
}
var africaInfo = new ContinentInfo("kenya egypt");
var asiaInfo = new ContinentInfo("india china");
var americaInfo = new ContinentInfo("usa canada");
当然,如果你真的想要大陆的哈希,你可以这样做:
var continents = {};
continents["africa"] = new ContinentInfo("kenya egypt");
continents["asia"] = new ContinentInfo("india china");
continents["america"] = new ContinentInfo("usa canada");
这样可以按大陆名称查找,然后每个大陆结构都会有一个国家/地区列表,然后是其他任何数据:
var asiaCountries = continents["asia"].countries;