Click to See Complete Forum and Search --> : Re-using arrays


MonkeyBoy
12-08-2003, 09:03 AM
Hi

I did a search of this forum in an attempt to find an answer to my question, but didn't find what I was looking for.

My situation is that I want users to add to an array, then if they choose to, clear the contents of that array and then start again.

e.g.

user adds three number to array: 1345, 17347, 3535

I can play with this array as usual.

But when I do

arrList = null;

Then alert(arrList);

I get "null".

But when the user (me) re-adds a value (67468), I get

undefined, undefined, undefined, 67468.

I also tried looping through the array, replacing the values with "", but I want to use the .length property of the array.

So the basic question, is how do I reset an array?

Help without sarcasm would be appreciated.

clairec666
12-08-2003, 09:19 AM
I think you can just reassign the variable, var whatevervaribale = new Array(), and this should get rid of the old array and replace it with a new (empty) one

TheBearMay
12-08-2003, 09:24 AM
Quickest way to clear the array is to set the length property to zero, ie. arrayName.length=0;

MonkeyBoy
12-08-2003, 09:49 AM
Hmmm. Neither method works. I shall keep trying with other ideas (a colleague has given me some tips).

I tried this

for (i = 0; i <= arrList.length; i++){
arrList[i] = "";
}

But this froze up IE. Using null instead of "" did the same

Any other suggestions would be welcome!

clairec666
12-08-2003, 09:53 AM
What you tried should work okay. I don't know why it froze. The problem is with using that method (this is a little hard to explain!) : Say your user reset the script and entered three new values. Your script wouldn't recognise that there were three values, since it holds a few blank records as well.

MichaelM
12-08-2003, 10:03 AM
This works in IE, maybe it'll help...

<HTML>
<HEAD>
<script>
arrList = new Array();

function addToList() {
l = 0;
if(arrList.length > 0) {
var l = arrList.length;
}
arrList[l] = txt.value;
vals.innerHTML = "";
for(i=0; i<=l; i++) {
vals.innerHTML = vals.innerHTML + arrList[i] + " = arrList[" + i + "]<BR>"
}
vals.innerHTML = vals.innerHTML + arrList.length + " = Length of arrList<BR>"
}
function clearIt() {
arrList = new Array();
vals.innerHTML = "";
}

</script>
</HEAD>
<BODY>
<input id="txt"><input type="button" id="btn" onclick="addToList();">
<input type="button" id="btnClear" value="clear list" onclick="clearIt();">
<P id="vals">
&nbsp;
</P>
</BODY>
</HTML>

MonkeyBoy
12-08-2003, 10:07 AM
Ach, it was a bug elsewhere that was causing the problems :o I was using an integer variable as the index of the array and should have reset it to zero when I nulled the array.

Thanks for the help anyway.

Cheericals :)