Tyler
Tyler

Reputation: 1662

Array.push is being affected by post Array.unshift call

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.

http://jsfiddle.net/ce6us1jk/3/

Upvotes: 0

Views: 39

Answers (2)

Oriol
Oriol

Reputation: 288080

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 ]
  Λ          |
  |__________|

Upvotes: 1

Mex
Mex

Reputation: 999

You need to copy the array, otherwise it is passed by reference.

To copy the array, use:

pattern.slice(0)

Upvotes: 1

Related Questions