【问题标题】:Why is array.push() not working correctly?为什么 array.push() 不能正常工作?
【发布时间】:2019-02-02 06:38:18
【问题描述】:

我有一个函数可以从 firestore 数据库中返回一组菜肴。 使用 console.log 我检查我要推送的菜的格式是否正确,然后推送它。

最后我 console.log 来检查数组是否一切正常。 这是我得到的:

https://image.noelshack.com/fichiers/2019/05/5/1549048418-arraypush.png

switch (type) {
  case "Plats": {
    this.nourritureCollection.ref.get().then(data => {

      let platArray : Plat[] = [];
      data.docs.forEach(doc => {
        this.plat.name = doc.data().nourritureJson.name;
        this.plat.price = doc.data().nourritureJson.price;
        this.plat.ingredients = doc.data().nourritureJson.ingredients;
        this.plat.type = doc.data().nourritureJson.type;
        this.plat.availableQuantity = doc.data().nourritureJson.availableQuantity;
        this.plat.isAvailableOffMenu = doc.data().nourritureJson.isAvailableOffMenu;
        this.plat.imgUrl = doc.data().nourritureJson.imgUrl;
        this.plat.temp = doc.data().nourritureJson.temp;
        console.log(this.plat)
        platArray.push(this.plat);
      });

      console.log(platArray)
      return platArray;
    });
    break;
  }...

plat 在我的服务组件中被实例化,我无法在我的函数中声明一个新的Plat()

预期的结果是我的菜品阵列中的菜品应该是不同的。

【问题讨论】:

  • 你每次推送同一个对象。
  • 你不断地只改变一个对象this.plat。在 forEach 中使用let plat :)
  • 是的,我不知道它为什么会这样。我虽然它会用新属性替换旧属性。我之前尝试创建一个新对象,但由于一些阻塞的范围而无法奇怪:/

标签: node.js angular ionic-framework


【解决方案1】:

您将在每次迭代中更新this.plat。所以它会有n数组中指向同一个对象的引用数,因此,所有数组元素的值将是this.plat的最后更新值

您需要为每次迭代创建 new Plat 对象。

data.docs.forEach(doc => {
        let plat: Plat = new Plat();
        plat.name = doc.data().nourritureJson.name;
        plat.price = doc.data().nourritureJson.price;
        plat.ingredients = doc.data().nourritureJson.ingredients;
        plat.type = doc.data().nourritureJson.type;
        plat.availableQuantity = doc.data().nourritureJson.availableQuantity;
        plat.isAvailableOffMenu = doc.data().nourritureJson.isAvailableOffMenu;
        plat.imgUrl = doc.data().nourritureJson.imgUrl;
        plat.temp = doc.data().nourritureJson.temp;
        console.log(plat)
        platArray.push(plat);
      });

正如评论中所指出的,如果Platclass,则只能使用new Plat(),如果是interface,则只需let plat:Plat; 即可。

【讨论】:

  • 我们知道 Plat 是一个类还是一个接口?
  • 好吧,现在实际上在查看链接的图像时,plat 确实是一个类:P 但是,是的,它在 OP 的问题中并没有真正清楚地显示出来......所以......我'我原谅了,对吧? :D(我没有投反对票)
  • Plat 是一个类,它可以工作(我之前尝试过无法让它工作,因为一些阻塞的范围不知道为什么......)。还是谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-07-16
  • 2019-01-04
  • 2020-09-03
  • 2016-10-10
  • 2016-10-24
  • 2017-02-27
  • 2017-07-08
  • 2014-11-23
相关资源
最近更新 更多