使用JS数组的push方法:报错Cannot set property 'push' of undefined

声明了JavaScript数组之后,用push方法给这个数组增加内容,运行时报错:
Uncaught TypeError: Cannot set property 'push' of undefined

clipboard.png

核心代码:

var hearts=[]; //心的数组
    function init (){ //初始化画布的大小
        canvas.width = wW;
        canvas.height = wH;
        for(var i=0; i<num; i++){
            hearts.push=new Heart();  //push
        }
        console.log(new Heart());
        requestAnimationFrame(render);
    }
    

如果不用push方法,直接hearts[i] = new Hearts();
报这个错:
clipboard.png

全部代码:

<body>
<canvas></canvas>
<script>
    var canvas = document.querySelector('canvas');
    var ctx = canvas.getContext('2d');
    var wW = window.innerWidth;
    var wH = window.innerHeight;
    var num = 100; //红心的数量
    var heartImage = new Image();   //创建一个新的image对象
    heartImage.src = "./heart.svg";
    heartImage.onload = render;
    init(); //运行初始化函数

    var hearts=[]; //心的数组
    function init (){ //初始化画布的大小
        canvas.width = wW;
        canvas.height = wH;
        for(var i=0; i<num; i++){
            hearts.push=new Heart();
        }
        console.log(new Heart());
        requestAnimationFrame(render);
    }

    function Heart(){   //构造函数
        this.x = Math.random() * wW;
        this.y = Math.random() * wH;
        this.opacity = Math.random() * .5 + .5;
        this.vel = {   //位移参数 移动量和方向
            x: (Math.random()-.5) * 4,
            y: (Math.random()-.5) * 4
        };
        this.initialW = 470;
        this.initialH = 410;
        this.initialW*.3;
        this.initialH*.3;
        this.targetScal = Math.random() * .3 + .02;  //最终大小缩放比例
        this.scale = this.targetScal * Math.random();

    }
        Heart.prototype.update = function(){
            this.x += this.vel.x;
            this.y += this.vel.y;
            this.scale += (this.targetScal - this.scale) * .1; //慢慢放大
            this.width = this.scale * this.initialW;
            this.height = this.scale * this.initialH;
        };

        Heart.prototype.draw = function(){
            ctx.globalAlpha = this.opacity;
            ctx.drawImage(heartImage, this.x, this.y, this.width, this.height)
        };

    var nHeart = new Heart();
    function render(){ //渲染函数
            ctx.clearRect(0, 0, wW, wH); //清空画布
            nHeart.update();
            nHeart.draw(); //对象的绘制方法
            requestAnimationFrame(render);
        }
</script>
</body>


求大佬们解答
阅读 12.2k
3 个回答

函数声明会提升,变量声明可不会提升。
你的代码中,执行init();时变量hearts还没声明。
先声明var hearts = [];
再执行init();
就可以了
另外hearts.push(new Heart());//push是这样用的

push是方法,不是属性,多看文档

hearts.push = ""这样是给在hearts创建了一个push属性。
应该是hearts.push(new Heart()),这样就调用了Array下的push方法,多去了解下js原型链。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题