如何在JavaScript中将相同的元素插入到数组中?
我有一个对象数组。但是当我插入我之前添加的对象时,它将覆盖我以前的对象。我该如何解决它?如何在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数组中时,它都会检查它是否会覆盖第一个元素的数据。
你应该使用拼接
http://www.w3schools.com/jsref/jsref_splice.asp
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("Added: " + fruits.splice(2,0,"Lemon") + "<br />");
document.write(fruits);
</script>
Added:
Banana,Orange,Lemon,Apple,Mango
[不要使用](http://w3fools.com)w3schools作为参考。它不仅与w3c无关,而且我们也有像MDN这样的适当引用来代替。另外,您的示例使用document.write(eeew!) – hugomg
其来自w3schools的示例。 –
@missingno试图说的是,w3schools不是一个很好的资源。事实上,他们的大部分信息都是不正确的,他们的知名度很大程度上是由于他们在网络上的悠久历史和在搜索引擎索引中的高分。 [MDN](http://developer.mozilla.org)是一个更好的链接资源。 –
这是你如何add an element to an array。这样,没有什么会被覆盖:
var sports = ["soccer", "baseball"];
sports.push("football", "swimming");
请发布您的代码,没有它你的问题就没有意义了。 –
没有看到代码就很难理解。但我想你可能使用相同的索引来保持对象。最好先备份数组,然后向其中添加新对象,然后将该备份复制到原始数组中。 – Naved
encurrentWeapon是一个全局变量 – Newbie