code below is the same as code you give,but it is more easy to understand:
function myArr(array){
array = array + array;
return array;
}
var arr = new Array(1,3,2,5);
myArr(arr);
document.write(arr); // Output : 1,3,2,5
arr = arr + arr;
document.write(arr); // Output : 1,3,2,51,2,5
Look out!!! arr
is the global variable while array
is the partial variable.
If you change array
in myArr
to arr
,that doesn't matter.
Ppartial variable only exists when the function is running except closure.
Explanation is in the comment:
var arr = new Array(1,3,2,5);//arr=[1,3,2,5];
myArr(arr);
function myArr(array){//array=[1,3,2,5],array===arr;
array = array + array;//array=1,3,2,51,3,2,5;arr didn't change!!!
return array;//return 1,3,2,51,3,2,5;arr still didn't change!!!
}
document.write(arr);//arr=[1,3,2,5],so you see 1,3,2,5
arr = arr + arr;//arr=1,3,2,51,3,2,5
document.write(arr);//so you see 1,3,2,51,3,2,51,3,2,5 because it didn't erase the last content.In this case,document write 1,3,2,51,3,2,5 after 1,3,2,5