鍍金池/ 問答/HTML5  HTML/ 使用JS數(shù)組的push方法:報錯Cannot set property 'pus

使用JS數(shù)組的push方法:報錯Cannot set property 'push' of undefined

聲明了JavaScript數(shù)組之后,用push方法給這個數(shù)組增加內(nèi)容,運行時報錯:
Uncaught TypeError: Cannot set property 'push' of undefined

clipboard.png

核心代碼:

var hearts=[]; //心的數(shù)組
    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; //紅心的數(shù)量
    var heartImage = new Image();   //創(chuàng)建一個新的image對象
    heartImage.src = "./heart.svg";
    heartImage.onload = render;
    init(); //運行初始化函數(shù)

    var hearts=[]; //心的數(shù)組
    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(){   //構(gòu)造函數(shù)
        this.x = Math.random() * wW;
        this.y = Math.random() * wH;
        this.opacity = Math.random() * .5 + .5;
        this.vel = {   //位移參數(shù) 移動量和方向
            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(){ //渲染函數(shù)
            ctx.clearRect(0, 0, wW, wH); //清空畫布
            nHeart.update();
            nHeart.draw(); //對象的繪制方法
            requestAnimationFrame(render);
        }
</script>
</body>


求大佬們解答
回答
編輯回答
墨小白

hearts.push = ""這樣是給在hearts創(chuàng)建了一個push屬性。
應該是hearts.push(new Heart()),這樣就調(diào)用了Array下的push方法,多去了解下js原型鏈。

2018年5月5日 18:25
編輯回答
毀了心

push是方法,不是屬性,多看文檔

2018年2月7日 01:30
編輯回答
維他命

函數(shù)聲明會提升,變量聲明可不會提升。
你的代碼中,執(zhí)行init();時變量hearts還沒聲明。
先聲明var hearts = [];
再執(zhí)行init();
就可以了
另外hearts.push(new Heart());//push是這樣用的

2018年9月11日 10:48