简体   繁体   中英

How to push all objects in class into one array javascript?

I'm trying to make language learn app and i have a problem. I have class "Word"

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

and lots of objects like

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

and I honestly don't have idea how to push all objects into one array. Can I use 'foreach' on every class object? Or is there a better solution for this?

You can push class objects into an Array without any issue:

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

But depending on your needs, you could put something like this directly into the constructor and have it collect all of the items it's constructed for you:

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;
    }
}

With this every time you construct an instance it's added to the external array. If you need to get everything from the array you can call Word.getInstances() or Word.clearInstances() if you want to empty it.

You have to declare a global array where all instances will be pushed to

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();

Let's build up your problem in natural language before we write some code:

A Word has its nativ and translation. A Word is stored in a Dictionary . You can add translations to a Dictionary and so on..

For that the array would be hide in a Dictionary like

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

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

    // more ..
}

Code Snippet

 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() 

Improvement

I suggest to use a Map instead of an Array . If the Dictionary will be extended by methods for finding words than you have to find the words in an Array by your self..

 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[word.englishWord] = word.polishWord } getTranslation(english) { return this.words[english] } 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') dictionary.addTranslation(intimate) console.log(dictionary.getTranslation('intimate')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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