0

I used the method described here:

How do I empty an array in JavaScript?

to reset an array in my code.

My code is such

var check = new Array();
var i = 0;

if(some statements){
    check[i]=something;
    i=+1;
}

function reset(){
    check.length=0;
}

After executing of if statement, if I console.log(), the array is displayed as such

["abc","def","ghi"]. Then the reset function is called.

After that, the next time the array is used, it logs as follows:

[1: "abc", 2: "def", ...]

What can I do to make it reset to original empty array?

Community
  • 1
  • 1
Newtt
  • 6,050
  • 13
  • 68
  • 106

2 Answers2

5

You can simplify your whole code using:

var check = [];

if(some statements)
{
    check.push(something);
}

function reset()
{
    check = [];
}

It may be better to refactor your code though. check may be out of scope inside the function, so you should try:

var check = [];

if(some statements)
{
    check.push(something);
}

function reset()
{
    return [];
}

check = reset();
BenM
  • 52,573
  • 26
  • 113
  • 168
  • While `check = []` will definitely *clear* the array, it does so by creating an entirely new array; if there are any references to the original one, this will break them... – newfurniturey Jan 15 '14 at 14:26
  • The problem seems to be that `check.length = 0;` is apparently not working for the OP (when it should), but you haven't explained why. – j08691 Jan 15 '14 at 14:27
  • Exactly. Nevertheless, I fixed it by resetting the variable `i`. – Newtt Jan 15 '14 at 14:28
  • But you don't need to use the `i` variable at all? – BenM Jan 15 '14 at 14:28
0

Try this:

function reset() {
  check.splice(0, check.length);
}
  • this will retain the same array, only the elements will be discared –  Jan 15 '14 at 15:18