Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having problems with the next code:

test1 = [0,0];
function func(test)
{
    var test2 = new Array();
    for(var i = 0; i < test.length; i++)
    if(test[i] == 0)
    {
        test[i] = 1;
        test2.push(test);
        test[i] = 0;
    }
    return test2;
}
a = func(test1);
document.write(a[0].toString()+"<br/>");
document.write(a[1].toString());

and the output is:

0,0
0,0

I have already checked with the console: when I change test[i] inside the condition, after test2.push(test), test2[test2.length] is also changed. (WHY?)

Is there a scope problem? What should I do to get an output like this?

1,0
0,1

Thanks.

share|improve this question
1  
a = func(test); //what is test here?? – linuxeasy Mar 7 '12 at 6:55
Upsss... corrected. It is test1. – Atoso Mar 7 '12 at 7:01

2 Answers

Use slice to create a copy of array:

var a = [1,2,3]
var b = a.slice();
b[0] = 0;
a[0] == 1;
share|improve this answer
  test2.push(test);

This doesn't create a copy of your test array, but just stores a new reference to your input array. So all your function does, is to store a multitude of references to the same input parameter. If you want to store a real copy use this:

 test2.push( test.slice(0) );
share|improve this answer
@user1150525, both answers solved my problem. Thanks :D – Atoso Mar 7 '12 at 7:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.