我有一个对象数组。但是当我插入我之前添加的对象时,它将覆盖我之前的对象。我该怎么解决它呢?
我有一个叫做player的对象。在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.location是一个固定的位置,直到它发生变化。我检查了一下,每次将与第一个元素相同的对象添加到onFieldWeapon数组中时,它都会覆盖第一个元素的数据。
发布于 2011-11-21 22:02:14
当您将同一对象多次插入到数组中时,数组中将有多个条目,这些条目都是对同一底层对象的引用。在下面的示例中,myArray中的所有三个条目以及x、y和myObj变量都指向相同的基础对象,因此,如果您通过其中一个数组项更改对象的属性,并不是因为它也更新了其他数组项,而是因为其他数组项指向您刚刚更改的同一对象:
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()函数需要更复杂--通常会使用某种形式的递归。
https://stackoverflow.com/questions/8212309
复制相似问题