繁体   English   中英

如何找到具有构造函数参数等于输入的Class的特定新对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM