我有一個對象數組。但是當我插入我之前添加的對象時,它將覆蓋我以前的對象。我該如何解決它?如何在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