简体   繁体   English

无法在存储到对象数组中设置对象属性(JavaScript)

[英]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. 问题是您试图将invader用作基础对象,这会使所有入侵者都引用同一对象。

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. 然后将newInvader的属性更改为所需的属性,然后将newInvader添加到数组而不是invader。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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