JavaScript remove array
I tried doing delete weapons[i];
but even do when I do weapons.length
I still get 1. Even though it should be 0. How do I definitely remove an array from weapons[]
array?
I comb over the weapons array by doing this:
for (var i = 0, setsLen = weapons.length; i < set开发者_如何学PythonsLen; ++i ) {
var searchWeapon = weapons[i].split("|");
// console.log('['+i+'] >> Weapon ID: ' + searchWeapon[0] + ' | Y: ' + searchWeapon[1] + ' | X: ' + searchWeapon[2]);
if (searchWeapon[1] == Y && searchWeapon[2] == X) {
delete weapons[i];
}
}
and I store each array as 3|10|4
where 3
is weapon ID, 10
is Y, and 4
is X.
Check out the .splice method
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Using your example:
for (var i = 0, setsLen = weapons.length; i < setsLen; ++i ) {
var searchWeapon = weapons[i].split("|");
if (searchWeapon[1] == Y && searchWeapon[2] == X) {
weapons.splice(i,1);
}
}
Use splice
array.splice(index,howmany)
If your array doesn't need to be sorted, you could use array.pop()
as it's extremely fast.
if(index == array.length-1) array.pop();
else array[index] = array.pop();
This method doesn't need to re-index everything after what you've splice()'d
, so it remains quick whether your array has a length of 5 or 350,000.
Additional to the answers above: you should walk the array from the end to the start, otherwise you'll miss elements inside the loop if a item has been removed. Demo: http://jsfiddle.net/doktormolle/2f9Ye/
delete
ing an array element leaves a hole behind with undefined
left in the element's place. You probably want to use Array.splice
.
var myArray = [1,2,3];
delete myArray[1]; // myArray is now [1, undefined, 3];
var myArray2 = [1,2,3];
myArray2.splice(1,1); // myArray2 is [1, 3]
To remove an element from an array use the splace
method. Example:
var myArr = ["apple", "orange", "pear"];
alert(myArr.length); // 3
myArr.splice(1,1); // start at 1th index (i.e 2nd element), remove 1 element
alert(myArr.length); // 2
for (var i=0; i<myArr.length; i++) alert(myArr[i]); // "apple", "pear"
精彩评论