我有一個對象數組。但是當我插入我之前添加的對象時,它將覆蓋我以前的對象。我該如何解決它?爲什麼我不能在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數組中時,它都會檢查它是否會覆蓋第一個元素的數據。
我不知道如果我理解你的問題,但我注意到,推encurrentWeapon到數組中,並寫在0指數總是安慰項目。可能你應該訪問ai.onFieldWeapon [ai.onFieldWeapon.length - 1]項。 – Krzysztof
我嘗試過,但不會工作。無論如何感謝 – Newbie
你能在你創建玩家對象的地方發佈代碼嗎? – Krzysztof