As we know that splice
mutates the localArray
for each iteration in the form loop, and also from the code I can see that the localArray grows in size by 1 for every i++
.
Hope this pseudocode below helps you understand the issue clearer.
Given arr1 = [1,2,4] and arr2 = [3,5,6]
localArray = [3,5,6]
localArray now equals [ 3,5,1,6]
if i = 0 and n = 2 then arr[i] = 1 so localArray.splice(2, 0, 1) equals [ 3,5,1,6]
next, if i = 1 and n = 3 then arr[i] = 2 so localArray.splice(3, 0, 2) equals [ 3,5,1,2,6]
Let’s say that if you were to take away the n++
, then the pseudocode would look like this:
Given arr1 = [1,2,4] and arr2 = [3,5,6]
localArray = [3,5,6]
if i = 0 and n = 2 then arr[i] = 1 so localArray.splice(2, 0, 1) equals [ 3,5,1,6]
localArray now equals [ 3,5,1,6]
next, if i = 1 and n = 2 then arr[i] = 2 so localArray.splice(2, 0, 2) equals [3,5,2,1,6]
Keep in mind that while n
remains unchanged, the indexed number in the array (arr[n]
) does change.
Now this should be clear that without the n++
thingy, it would produce the effect that you’ve been wondering about.