【问题标题】:How to push all objects in class into one array javascript?如何将类中的所有对象推送到一个数组javascript中?
【发布时间】:2019-06-07 08:50:32
【问题描述】:

我正在尝试制作语言学习应用程序,但遇到了问题。我有“单词”类

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”吗?还是有更好的解决方案?

【问题讨论】:

  • 我不确定我是否明白你在问什么。为什么你需要一个数组而不是某种负责构建和记录单词的WordManager 类,比如class WordManager { constructor() {} create(word, mapping) { let w = new Word(word, mapping); this.words.push(w); return w; },或者更好的是,为什么不制作一个字典而不是使用单个单词实例呢?特别是考虑到 JS 对象已经是字典:const words = {}; words["intimate"] = "intymny/prywatny"; 并从那里获取?

标签: javascript arrays oop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢!就是这样:)
    • 太棒了........
    【解决方案3】:

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

    // 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(),如果您想清空它。

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多