简体   繁体   中英

Unable to set object property in storing to an array of objects (JavaScript)

I'm trying to create an array of objects for a simple canvas-based Space Invaders game. I have created a space invader object, and an array of space invaders. I want to slightly change the horizontal position and other properties of each invader before it is added to the array. This is how I'm trying to do it:

// Invaders
invaders = new Array();
invader = {
    x: 0,
    y: 0,
    size: 25,
    xspeed: 0.25,
    yspeed: 0.1,
    alive: 1,
    letter: ""
};

invadersMovingLeft = true;
kills = 0;

word = "interesting";
numberOfInvaders = word.length;
letters = word.split('');
letterNumber = 0;
xpos = 0;
invaderSpacing = 50;
exploding = false;
shuffledLetters = shuffle(letters);
hitLetters = "";

for (i = 0; i < numberOfInvaders; i++) {
    invader['letter'] = shuffledLetters[letterNumber];
    invader['x'] = xpos;
    xpos = xpos + invaderSpacing;
    letterNumber = letterNumber + 1;
    invaders[i] = invader;
    console.log(invaders);
}

The console log shows that each invader has the exact same properties. Any idea what's going wrong here? I'm new at working with objects, and am probably making a beginner's mistake.

The problem is you are trying to use invader as a base object, which makes all of the invaders refer to the same object.

Instead of that, have an invader which acts like a class, that you can instantiate to make a new invader. Each invader is then a new independent instance, which you can push to the array.

function invader(){
    this.x = 0;
    this.y = 0;
    this.size = 25;
    this.xspeed = 0.25;
    this.yspeed = 0.1;
    this.alive = 1;
    this.letter = "";
}

var invaders=new Array();
var inv;

for(i=0;i<numberOfInvaders;i++){
    inv = new invader();
    inv.letter = shuffledLetters[letterNumber];
    inv.x = xpos;
    xpos = xpos+invaderSpacing;
    letterNumber = letterNumber+1;
    invaders.push(inv);
}

console.log(invaders);

Try adding

var newInvader = new invader(); 

to your loop. (first line)

Then change the properties of newInvader to what you want, then add newInvader to the array instead of invader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM