2011-11-21 50 views
0

我有一個對象數組。但是當我插入我之前添加的對象時,它將覆蓋我以前的對象。我該如何解決它?爲什麼我不能在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數組中時,它都會檢查它是否會覆蓋第一個元素的數據。

+0

我不知道如果我理解你的問題,但我注意到,推encurrentWeapon到數組中,並寫在0指數總是安慰項目。可能你應該訪問ai.onFieldWeapon [ai.onFieldWeapon.length - 1]項。 – Krzysztof

+0

我嘗試過,但不會工作。無論如何感謝 – Newbie

+0

你能在你創建玩家對象的地方發佈代碼嗎? – Krzysztof

回答

1

當您插入相同的對象到一個數組多次,你必須是相同的基礎對象的所有引用數組中的多個條目。在下面的例子中myArray所有三個條目和xymyObj變量都指向同一個底層對象,因此,如果您通過它不是陣列項目中的一個改變對象的屬性,它更新其他數組項太多,它是其他數組項指向你只是改變了相同的對象:

var myObj = { "p1" : "v1", "p2" : "v2" }; 
var myArray = []; 
// all of the following reference the same underlying object as myObj, 
// not copies of myObj. 
myArray.push(myObj); 
myArray.push(myObj); 
myArray.push(myObj); 
var x = myObj, 
    y = myObj; 
myArray[1].p1 = "new value"; 
alert(myArray[0].p1); // "new value" 
alert(x.p1); // "new value" 

這聽起來像你想要做的是創造什麼每次複製對象的使陣列中的每個項目是一個獨立的對象,您可以更新而不影響其他所有對象。不幸的是,JavaScript中沒有內置的方法。幸運的是這不是特別難寫你自己的對象複製功能,尤其是在你的情況,你似乎只有一個一維對象:

function copyObject(srcObj) { 
    // create new blank object and copy the direct properties one by one 
    var newObj = {}; 
    for (var k in srcObj) 
     if (srcObj.hasOwnProperty(k)) 
      newObj[k] = srcObj[k]; 
    return newObj; 
} 

var myObj = { "p1" : "v1", "p2" : "v2" }; 
var myArray = []; 
// make independent copies instead of just more references to the same object 
myArray.push(copyObject(myObj)); 
myArray.push(copyObject(myObj)); 
myArray.push(copyObject(myObj)); 
var x = copyObject(myObj), 
    y = copyObject(myObj); 
myArray[1].p1 = "new value"; 
alert(myArray[0].p1); // "v1" 

如果您有包含對象或數組那麼你copyObject()功能需求對象要更復雜 - 通常會使用某種形式的遞歸。

相關問題