我有一个对象数组。但是当我插入我之前添加的对象时,它将覆盖我以前的对象。我该如何解决它?如何在JavaScript中将相同的元素插入到数组中?
我有一个叫做player的对象。在玩家中,我有两个数组:一个叫onHandWeapon,一个叫onFieldWeapon。他们是武器对象的阵列。
function player(lp){
this.lp = lp;
this.onFieldWeapon = new Array();
this.onHandWeapon = new Array();
}
function weapon(id, heart, bullet, src){
this.id = id;
this.heart = heart;
this.bullet = bullet;
this.src = src;
this.location;
this.name;
this.discription;
this.bufferBullet = bullet;
}
我已经在onHandWeapon数组中设置了三个虚拟对象。然后,我想随机选取其中一个并将其放入onFieldWeapon中,并为其指定一个随机位置。
function aiCreateWeapon(){
var b = Math.floor(Math.random()*ai.onHandWeapon.length);
$('#console').append(' ' + b + ' ');
var ip = 100;
while($('#'+ip).attr('class') != 'enemyField'){
ip = Math.floor(Math.random()*48);
}
encurrentWeapon = ai.onHandWeapon[b];
var source = encurrentWeapon.src;
var oImg = document.createElement("img");
oImg.setAttribute('src', source);
oImg.setAttribute('height', '60px');
oImg.setAttribute('width', '60px');
$('#'+ip).append(oImg).show('explode','slow');
encurrentWeapon.location = ip;
ai.onFieldWeapon.push(encurrentWeapon);
$('#console').append(' ' + ai.onFieldWeapon[0].location + ' ');
}
aiCreateWeapon是一个绑定到按钮的函数。当我点击它时,ai.onFieldWeapon [0] .location是一个固定位置,直到它改变。每次当与第一个元素相同的对象被添加到onFieldWeapon数组中时,它都会检查它是否会覆盖第一个元素的数据。
请发布您的代码,没有它你的问题就没有意义了。 –
没有看到代码就很难理解。但我想你可能使用相同的索引来保持对象。最好先备份数组,然后向其中添加新对象,然后将该备份复制到原始数组中。 – Naved
encurrentWeapon是一个全局变量 – Newbie