如何将类中的所有对象放入一个数组javascript中?

时间:2019-01-12 19:56:45

标签: javascript arrays oop

我正在尝试使语言学习应用程序,但是我遇到了问题。我上了“单词”课程

class Word {
    constructor(englishWord, polishWord){
       this.englishWord = englishWord
       this.polishWord = polishWord
       this.displayTranslation = () =>{
          console.log(`${englishWord} = ${polishWord}`)
       }
    }
}

还有很多对象

const intimate = new Word('intimate', 'intymny/prywatny')
const insurance = new Word('insurance', 'ubezpieczenie')

老实说,我不知道如何将所有对象放入一个数组。我可以在每个类对象上使用“ foreach”吗?还是对此有更好的解决方案?

3 个答案:

答案 0 :(得分:1)

您可以毫无问题地将类对象推入数组:

// using your class declared above
const intimate = new Word('intimate', 'intymny/prywatny')
var array = [];
array.push(intimate);

但是根据您的需要,您可以将类似这样的内容直接放入构造函数中,并让它收集为您构造的所有项目:

const instances = [];
class Word {
    constructor(englishWord, polishWord){
        this.englishWord = englishWord
        this.polishWord = polishWord
        this.displayTranslation = () =>{
            console.log(`${englishWord} = ${polishWord}`)
        }
        Word.addInstance(this);
    }
    static addInstance(item){
        instances.push(item);
    }
    static getInstances(){
        return instances;
    }
    static clearInstances(){
        instances.length = 0;
    }
}

每次构建实例时,它都会被添加到外部数组中。如果您需要从数组中获取所有内容,则可以调用Word.getInstances()Word.clearInstances()来清空它。

答案 1 :(得分:1)

您必须声明一个全局数组,所有实例都将被推送到

const instances = [];

class Word {
    constructor(englishWord, polishWord){
        this.englishWord = englishWord;
        this.polishWord = polishWord;
        this.displayTranslation = () =>{
           console.log(`${englishWord} = ${polishWord}`);
        };
        instances.push(this);
    }

    static GetWords() {
        instances.forEach( x => {
            x.displayTranslation();
        });
    }       
}

new Word('intimate', 'intymny/prywatny');
new Word('insurance', 'ubezpieczenie');

Word.GetWords();

答案 2 :(得分:1)

在编写一些代码之前,让我们用自然语言来解决您的问题:

  

public class CustomerDetailValidator implements ConstraintValidator<ValidCustomer, CustomerDetails> { @Override public boolean isValid(CustomerDetails value, ConstraintValidatorContext context) { // Need some way here to fetch the current group applied on the QuoteDetail bean as I want to ensure // this validation is only invoked for specified groups. // Lets suppose there was 1 more endpoint /international with validation group InternationalCustomers, I don't want this validator to be called in that case. How can I do this. return true; } } 具有其原始性和翻译性。 Word存储在Word中。您可以将翻译添加到Dictionary中,依此类推。

为此,Dictionary会像

一样隐藏在array
Dictionary

代码段

class Dictionary {
    constructor() {
        this.words = []
    }

    addTranslation(word) {
        this.words.push(word)
    }

    // more ..
}

改进

我建议使用class Word { constructor(englishWord, polishWord) { this.englishWord = englishWord this.polishWord = polishWord this.displayTranslation = () => { console.log(`${englishWord} = ${polishWord}`) } } } class Dictionary { constructor() { this.words = [] } addTranslation(word) { this.words.push(word) } print() { for (let i = 0; i < this.words.length; i++) { this.words[i].displayTranslation() } } } const dictionary = new Dictionary() const intimate = new Word('intimate', 'intymny/prywatny') const insurance = new Word('insurance', 'ubezpieczenie') dictionary.addTranslation(intimate) dictionary.addTranslation(insurance) dictionary.print()代替Map。如果Array将通过查找单词的方法进行扩展,则您必须自己在Dictionary中查找单词。

Array