PDA

View Full Version : Remove items from array in IE5.0


Danne
05-14-2003, 09:35 PM
How can I remove items from an array-object in IE 5.0?

I'd like to decrease the length after removing the items, and I don't want to replace the array object with a new or another array.

The splice and shift methods are not supported in IE5.0, so I thought of creating these in JavaScript and download after a serverside browser-check.

I had something like this in mind:

/**
* Removes the first element from an array and returns that element.
* This method changes the length of the array.
*/
Array.prototype.shift = function() {
var temp=[];
var removed=this[0];
var ct = this.length-2;
for (var i=this.length-1;i>0;i--) {
temp[ct--]=this[i];
}
delete this[this.length-1];
for (var i=0;i<temp.length;i++) {
this[i]=temp[i];
}
return removed;
}

var arr=new Array("123","456","789");
arr.shift(); // Returns "123"
//arr: "456","789",undefined
//The original: "456","789"



But the length does not change. Another way would be to use a completely different function like this:

Array.remove=function(arr,index,howMany){
var removed=new Array();
var ct=Math.min(arr.length-howMany,arr.length);
var ct2=arr.length-ct;
for (var i=arr.length-1;i>=0;i--) {
if(i<index || i>(index+howMany)){
//keep
}else {
removed[ct2--]=arr[i];
delete arr[i];
}
}
return removed;
}

var arr=new Array("123","456","789");
Array.remove(arr,0,1); // Returns "123"
//arr: "456","789",undefined



Obviously with the same result, since delete array[index], doesn't change the length.

Any ideas??

Danne
05-14-2003, 09:46 PM
Sorry, ignore that. I just discovered that
arr.length=arr.length-1;
actually works, so...:rolleyes:

Some things are not as complicated as u would imagine...:o

liorean
05-14-2003, 09:54 PM
Yep, that works (array.length-- works, too). But, you can always have a look at this script I had lying around in my heap of almost-never-used scripts that I wrote some time ago. (This is a cleanup of the original, which wasn't at all as nicely written.)

http://codingforums.com/showthread.php?s=&threadid=19996

Danne
05-15-2003, 02:55 PM
It seems like what I'm looking for. Your script gives me a syntax error on line 8, though (using IE5.00.2920.000).

Anyway, I solved the problem changing the .length-property...

Thanx anyway..
:)

liorean
05-15-2003, 05:15 PM
Try it again now. I've changed the syntax to check for Array.prototype.function instead of [].function. It takes more space, but I'd guess it's more compatible.