Derek Basch wrote:
I can remove objects from an array by doing this:
for (i in oCache){
if (i == "test"){
delete oCache[i];
};
};
However, the array's length property is unaffected.
If I use splice like so:
for (i in oCache){
if (i == "test"){
oCache.splice(i, 1);
};
};
It breaks because oCache's length is altered within the loop by
splice.
How do I iterate though an array, remove items AND change the length
property?
Thanks,
Derek Basch
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>untitled</title>
<script type="text/javascript">
Array.prototype.dele = function()
{
for (var i = 0, l = arguments.length, arr = []; i < l; ++i)
{
for (var j = 0; j < this.length; ++j)
{
if (this[j] == arguments[i]
&& typeof this[j] == typeof arguments[i])
{
arr.push(this.splice(j, 1));
}
}
}
return arr;
}
var oCache = [
'el1' , 'el2' , '3' , 'test1' , 'el4' , 'test2'
];
a = window.alert;
a('oCache:\n\n' + oCache.join('\n'));
a('original length: ' + oCache.length);
a('call: oCache.dele(\'test1\')');
a('element removed: ' + oCache.dele('test1'));
a('oCache:\n\n' + oCache.join('\n'));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(\'test2\')');
a('element removed: ' + oCache.dele('test2'));
a('oCache:\n\n' + oCache.join('\n'));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(3)');
a('element removed: ' + oCache.dele(3));
a('oCache:\n\n' + oCache.join('\n'));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(\'el1\', \'el2\', \'3\', \'el4\')');
a('elements removed: ' + oCache.dele('el1', 'el2', '3', 'el4'));
a('oCache:\n\n' + oCache.join('\n'));
a('oCache length: ' + oCache.length);
</script>
</head>
<body>
</body>
</html>