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??
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??