...

View Full Version : Array in javascript



arungok
05-25-2012, 11:16 AM
when i copied a array to another variable and sorted the one, but its affecting the original array variable


function srt1 ()
{
arr2=arr1;
var srt=arr1.sort();
document.main.srt.value=srt;
}

where
arr1={9,8,3,6,7,1,4}
arr2={9,8,3,6,7,1,4}
after sorting
arr1={1,3,4,6,7,8,9}
arr2={1,3,4,6,7,8,9}

please give a answer, in advance Thank you

Lerura
05-25-2012, 12:12 PM
i can't tell you why it is made so all copies are affected, but I can give you a workaround.

srt= arr1.slice(0); makes srt become the result of slicing 0 elements from arr1 without being a direct copy of it.

This array can then be sorted without affecting the original array, nor direct copies of the original array.
srt.sort();

you can merge these to action in to a single command.

srt= arr1.slice(0).sort();

Philip M
05-25-2012, 12:24 PM
Assigning an array or an object to a variable makes a reference to the value.


<script type = "text/javascript">

function srt1() {
var arr1=[9,8,3,6,7,1,4];
var arr2 = arr1.slice(0); // copy the values to arr2
arr1.sort();
alert (arr1); // 1,3,4,6,7,8,9
alert (arr2); // 9,8,3,6,7,1,4
}

</script>Objects are trickier because there is no native method which returns a copy of the object. For more info see http://my.opera.com/GreyWyvern/blog/show.dml/1725165

He [John Terry] wears his shirt on his sleeve. - Commentator Sky Sports News

Dormilich
05-26-2012, 12:57 PM
Objects are trickier because there is no native method which returns a copy of the object. For more info see http://my.opera.com/GreyWyvern/blog/show.dml/1725165

note: it was not explicitly mentioned in the Article, but never try to copy (or deep-clone) DOM objects (they contain circular references that would get you stuck in infinite recursion)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum