There's only one array. If you were to alert(tmp), it also would be X,B.
Unlike a literal string value which is copied when another variable or reference is set equal to it, an array is an object. Unless you make a new array that is a copy of it, it's the same array regardless of how many variables or other references you assign it to.
There are I suppose various ways to copy an array. Two that spring to mind are:
Code:
<script type="text/javascript">
function test(T) {
this.a = [];
this.b = [];
for (var i = T.length - 1; i > -1; --i){
this.a[i] = this.b[i] = T[i];
}
// As expected both a and b display "A,B"
alert("a Before : "+this.a+"\nb Before : "+this.b);
// only update b
this.b[0]="X";
// the arrays a, b and T(tmp) are separate now. a and T(tmp) are still A,B, b is X,B
alert("a After : "+this.a+"\nb After : "+this.b);
}
var tmp=new Array("A","B");
theTest=new test(tmp);
</script>
And:
Code:
<script type="text/javascript">
function test(T) {
this.a = [].concat(T);
this.b = [].concat(T);
// As expected both a and b display "A,B"
alert("a Before : "+this.a+"\nb Before : "+this.b);
// only update b
this.b[0]="X";
// the arrays a, b and T(tmp) are separate now. a and T(tmp) are still A,B, b is X,B
alert("a After : "+this.a+"\nb After : "+this.b);
}
var tmp=new Array("A","B");
theTest=new test(tmp);
</script>
Bookmarks