We can assign one array to another array as we assign a variable:
var nums = []; for (var i = 0; i < 10; ++i) { nums[i] = i+1; } var samenums = nums;
When assigning one array to another array, we are assigning a reference to the assigned array.
The two variable are pointing to the same object in the memory.
When changing to the original array, that change is reflected in the other array as well.
The following code demonstrates how this works:
var nums = []; for (var i = 0; i < 100; ++i) { nums[i] = i+1; } var samenums = nums; nums[0] = 400; console.log(samenums[0]);
The code above generates the following result.
This is called a shallow copy.
Other than shallow copy we what we did in the code above we can also do deep copy on array object.
The deep copy means the array elements are stored in two separate memory locations and two array variable are pointing to two different address in memory.
To make a deep copy, so that each of the original array's elements is actually copied to the new array's elements.
function copy(arr1, arr2) { for (var i = 0; i < arr1.length; ++i) { arr2[i] = arr1[i]; } } var nums = []; for (var i = 0; i < 100; ++i) { nums[i] = i+1; } var samenums = []; copy(nums, samenums); nums[0] = 400; console.log(samenums[0]);
The code above generates the following result.
We can print out arrays contents with console.log()
function.
For example:
var nums = [1,2,3,4,5]; console.log(nums);
will produce the following output:
1,2,3,4,5