为什么我不能't在javascript中插入相同的元素到数组中?

Why couldn't i insert the same element into an array in javascript?

本文关键字:插入 元素 数组 javascript 不能 为什么      更新时间:2023-09-26

我有一个对象数组。但是当我插入之前添加的对象时,它将覆盖之前的对象。我怎么解决它?

我有一个对象叫做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]。位置是一个固定的位置,直到它改变。我有检查,每次当对象是相同的第一个元素,被添加到onFieldWeapon数组,它会覆盖第一个元素的数据。

当您多次将同一个对象插入到数组中时,数组中的多个条目都是对同一个底层对象的引用。在下面的示例中,myArrayx以及ymyObj变量中的所有三个条目都指向相同的底层对象,因此,如果您通过其中一个数组项更改对象的属性,则不是它也更新了其他数组项,而是其他数组项指向您刚刚更改的相同对象:

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()函数需要更复杂-通常会使用某种形式的递归