Consider the following code
function frankenSplice(arr1, arr2, n) {
let finalArray = arr2;
finalArray.splice(n, 0, ...arr1)
console.log(arr2)
return finalArray;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
console.log(arr2)
returns [4, 1, 2, 3, 5, 6]
Is finalArray just a pointer to arr2? I am a little confused about how the manipulation of arr2 is achieved.
You would be right that they both point to the same array. We can see this by modifying an array set to another array:
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr2.push(4);
console.log(arr1);
Likewise it would follow that .splice()
would modify it too:
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr2.splice(2);
console.log(arr1);
We see this also when we pass an array to a function and modify it:
function foo(arr) {
arr.push(3);
}
const arr = [1, 2];
foo(arr);
console.log(arr);
1 Like
system
Closed
3
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.