I am pushing an array to a second array then unshifting and popping the first array but for some reason this is affecting the second one. Why is this? I would like resultsList to equal [0,1,0,0]
but it ends up being [0,0,1,0]
var pattern = [0,1,0,0];
var resultsList = [];
resultsList.push( pattern );
pattern.unshift( pattern.pop() );
console.log( resultsList );
Here is a JSFiddle to make it easier to comprehend.
You need to copy the array, otherwise it is passed by reference.
To copy the array, use:
pattern.slice(0)
pattern.pop()
removes and returns the last item in pattern
.
pattern.unshift(item)
adds item
at the beginning of pattern
.
So the output is expected:
[ 0, 1, 0, 0 ]
Λ |
|__________|
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.