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?

5
  • What's wrong with arr.push()? Commented Jan 15, 2014 at 14:24
  • I think it's i+=1; too. I don't think you can have it round the other way. Commented Jan 15, 2014 at 14:24
  • The answer is in the question you linked... Commented Jan 15, 2014 at 14:26
  • 1
    No repro: jsfiddle.net/j08691/3S9T3 Commented Jan 15, 2014 at 14:26
  • possible duplicate of How to empty an array in JavaScript? Commented Jan 15, 2014 at 14:26

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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...
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.
Exactly. Nevertheless, I fixed it by resetting the variable i.
But you don't need to use the i variable at all?
0

Try this:

function reset() {
  check.splice(0, check.length);
}

1 Comment

this will retain the same array, only the elements will be discared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.