最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin7浏览0评论

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?

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?

Share Improve this question edited Jan 12, 2019 at 20:05 0.sh 2,75221 silver badges40 bronze badges asked Jan 12, 2019 at 19:56 kaziutuskaziutus 1483 silver badges10 bronze badges 1
  • 2 I'm not sure I understand what you're asking. Why would you need an array instead of some kind of WordManager class that is responsible for building and recording words, a la class WordManager { constructor() {} create(word, mapping) { let w = new Word(word, mapping); this.words.push(w); return w; }, or better yet, why not make a word dictionary instead of using individual word instances? Especially given that JS objects are already dictionaries: const words = {}; words["intimate"] = "intymny/prywatny"; and take it from there? – Mike 'Pomax' Kamermans Commented Jan 12, 2019 at 20:09
Add a ment  | 

3 Answers 3

Reset to default 3

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

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.

发布评论

评论列表(0)

  1. 暂无评论