Как поместить все объекты в классе в один массив javascript? - PullRequest
0 голосов
/ 12 января 2019

Я пытаюсь сделать приложение для изучения языка, и у меня есть проблема. У меня есть класс "Слово"

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 голосов
/ 12 января 2019

Вы должны объявить глобальный массив, в котором все экземпляры будут помещены в

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();
0 голосов
/ 14 января 2019

Давайте создадим вашу проблему на естественном языке, прежде чем писать код:

A 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 самим собой.

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'))
0 голосов
/ 12 января 2019

Вы можете помещать объекты класса в массив без каких-либо проблем:

// 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(), если хотите очистить его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...