0

i have a main array as

  arrayVariable = [1,2,3];

and i want another to variables to have the same content as above. If i do

anotherVariable = arrayVariable;

It will just reference that array and they wont be independent of each other. I tried this solution, but it didnt work.

 var anotherVariable = arrayVariable.slice();

Edit: Another question, while passing array through a function, does it pass the array or is it passed by reference?

like

 var array = [];
 someFunction(array);

 function someFunction(array){};
3
  • .slice() should work. Can you give an example where it doesn't? Commented Dec 22, 2015 at 10:24
  • does a function pass the reference of the array? question updated. Commented Dec 22, 2015 at 10:30
  • it's an object, so by reference Commented Dec 22, 2015 at 10:33

3 Answers 3

3

Check the below code, look they are independent.

arrayVariable = [1,2,3];
var anotherVariable = arrayVariable.slice(); // or .concat()

arrayVariable[0] = 50; // Hopefully it should not change the value of anotherVariable
alert(anotherVariable); // Look value of anotherVariable is not changed

Sign up to request clarification or add additional context in comments.

Comments

0

you can try

var aa = [1,2,3,4,5,6];

var bb = [].concat(aa);//copy aa array to bb, they are now independent of each other.

hope helps.

Comments

0

You can do it using a loop.

arrayvariable=[1,2,3];
for (var i=0;i<arrayvariable l.length;i++)
//while could also be used.
{ 

    anothervariable[i]=arrayvariable[i];
}

Comments

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.