首页 > 解决方案 > 无法将对象推入数组,因为它是未定义的 Javascript

问题描述

我正在尝试将 Card 类型的对象推送到数组中,但我得到:
无法读取未定义的属性“推送”。
这是班级卡片:

class Card {
    
    constructor(value, suit) {
        this.Value = value;
        this.Suit = suit;
        this.Viewed = false;
    }
}

这是班级游戏:<br/ >

class Game{
    construct(){
        this.GroundCards = []; //This is the array i am trying to push objects at.
        this.GroundCard = null;
        this.NbCardsPickedSeven = 0;
    }

    pushCard(card){
        console.log(this.GroundCards);
        this.GroundCards.push(card);
    }
}

当我这样做时console.log(this.GroundCards);,它会将 undefined 打印到控制台中,然后给我一个错误。
有人能告诉我为什么首先未定义 GroundCards 属性吗?
我还尝试在构造函数中对其进行初始化,例如:
this.GroundCards = new Array();它仍然无法正常工作。
我对 Javascript 语法还是有点陌生​​,对于任何明显的错误,我深表歉意。
谢谢你的时间。

标签: javascriptarraysundefinedes6-class

解决方案


您的构造函数被命名construct- 因此它永远不会被调用。应该叫它constructor


推荐阅读