[英]How can i find specific new object of Class that has a constructor argument equal to input
我有一個名為Country的類,帶有4個構造函數參數。
然后,我使用指定的值從該類創建一些新的國家/地區。
我的問題是,如何創建一個方法,可以找到並返回一個this.value等於方法輸入的對象?
class Country {
constructor(name, area, population, topdomain) {
this.name = name;
this.area = area;
this.population = population;
this.topdomain = topdomain;
}
static findCountry = domain => {
/*Here is where the magic should happen.
If domain is in any of the countries below, then it should return the country name.
*/
}
}
norway = new Country("Norway", 323802, 5320045, ".no");
sweden = new Country("Sweden", 450295, 9960487, ".se");
russia = new Country("Russia", 17098242, 142257519, ".ru");
china = new Country("China", 9596960, 1379302771, ".cn");
這個函數應該返回“Norway”:
Country.findCountry(".no");
要使其工作,該類必須保留所有已創建實例的列表。 由於JS沒有弱引用,這意味着沒有任何實例可以被垃圾收集(所以要小心):
static instances = [];
constructor(/*...*/) {
/*...*/
Country.instances.push(this);
}
static findCountry = domain => {
return this.instances.find(country => country.domain === domain);
}
不要來這里要求別人寫你的代碼;)
class Country {
constructor(name, area, population, topdomain) {
this.name = name;
this.area = area;
this.population = population;
this.topdomain = topdomain;
Country._ALL.push(this);
}
static findBy(key, value) {
let output = [];
for ( let i in Country._ALL) {
let c = Country._ALL[i];
if (c.hasOwnProperty(key) && c[key] === value)
output.push(c);
}
return output;
}
}
Country._ALL = [];
警告! ES6類不支持靜態變量,如static variable = [];
如果你想在ES6中使用靜態類變量,你必須使用ClassName.variable = [];
之后類的聲明。
你的類不知道你在某處實例化的4個對象。 您需要將它們放在一個集合(例如數組)中,然后在搜索方法中顯式引用該集合:
class Country {
constructor(name, area, population, topdomain) {
this.name = name;
this.area = area;
this.population = population;
this.topdomain = topdomain;
}
static findCountry(domain) {
return (knownCountries.find(country => country.topdomain == domain) || {}).name;
// ^^^^^^^^^^^^^^
}
}
const norway = new Country("Norway", 323802, 5320045, ".no");
const sweden = new Country("Sweden", 450295, 9960487, ".se");
const russia = new Country("Russia", 17098242, 142257519, ".ru");
const china = new Country("China", 9596960, 1379302771, ".cn");
const knownCountries = [norway, sweden, russia, china];
// ^^^^^^^^^^^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.