It seems like I might be making a simple mistake here. Essentially, I have an array that I am passing into a function. My goal is to remove one element from the array, perform certain operations on it, and then iterate through the remaining elements of the array until there are none left. Once the array is empty, I want to go back and start over with the original array.
However, I'm encountering a strange issue when using array.shift(). It appears to be affecting the wrong variable, if that even makes sense.
Let me provide an abstract example:
var originalArray = [1,2,3,4,5,6,7,8,9]
function goThroughArray(array){
var untouchedArray = array
console.log('untouched array before is ' + untouchedArray)
var insideArray = untouchedArray
console.log('inside array is ' + insideArray)
var removedNumber = insideArray.shift()
console.log('removed number: ' + removedNumber + ' from insideArray')
console.log('inside array after is ' + insideArray)
console.log('untouched array after is ' + untouchedArray)
}
goThroughArray(originalArray)
The console log output shows:
untouched array before is 1,2,3,4,5,6,7,8,9
inside array is 1,2,3,4,5,6,7,8,9
removed number: 1 from insideArray
inside array after is 2,3,4,5,6,7,8,9
untouched array after is 2,3,4,5,6,7,8,9
This is all happening without any looping involved. Can anyone clarify why calling shift() on insideArray also affects untouchedArray?
I would anticipate that only the first element of insideArray, stored as "removedNumber", would be removed. So why does untouchedArray lose its first element too?
EDIT
function addOne(number){
console.log('number in is: '+number)
var original = number;
var modified = original
console.log('original before is ' + original)
console.log('modified before is ' + modified)
modified++
console.log('original after is ' + original)
console.log('modified after is ' + modified)
}
addOne(1)
The output is:
number in is: 1
original before is 1
modified before is 1
original after is 1
modified after is 2
NEW EDIT
Even though this question is quite old, I wanted to update it with a simpler solution:
JSON.parse(JSON.stringify(obj))
This will create a copy of the object.