Can I Revert to Original Array After Modification?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
drayarms
Forum Contributor
Posts: 134
Joined: Fri Dec 31, 2010 5:11 pm

Can I Revert to Original Array After Modification?

Post by drayarms »

The topic may sound vague, so please read on to get the details clarified. Ok I have an array which I called deck as defined below. I remove the last two elements from this array using a function pop_array() that i constructed, and assign the resulting array (deck_minus_player1) to a new variable. Now I want to be able to manipulate both arrays, ie the original deck, and the new deck_minus_player1 created from it, independently. But it seems as if, everytime I run the pop_array() function which creates the new array from the old, the old array automatically morphs into the new one and doesn't retain all its original contents. So how do I keep my old array (deck) with all its contents unscathed, even after I perform an operation on it? Here's the code.

Code: Select all

<script type = "text/javascript" src="http://code.jquery.com/jquery-latest.js"> </script>
<script type = "text/javascript">

			function pop_array(num_popped,array){

				for(i=0; i<num_popped; i++){

					array.pop(); 

				} 

				return array;

			}//Function end




			var deck = ["one","two","three","four","five"];

			var deck_minus_player1 = pop_array(2,deck);


			for(i=0; i<deck.length; i++){

				alert(deck[i]);

			}



		</script>



So when I run this code, the output is one, two, three instead of one, two , three, four, five as I intended. But if I eliminate the var deck_minus_player1 = pop_array(2,deck); line, i get desired results.
Last edited by pickle on Wed Jun 06, 2012 10:54 am, edited 1 time in total.
Reason: Used proper syntax tags
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can I Revert to Original Array After Modification?

Post by requinix »

Because array.pop() removes something from the array. Removes. It's not there anymore.

array.slice
Post Reply