drayarms Posted June 6, 2012 Share Posted June 6, 2012 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. <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. Quote Link to comment Share on other sites More sharing options...
Stooney Posted June 14, 2012 Share Posted June 14, 2012 pop modifies the original array. So what's happening is you're changing the array, then copying it. You want to copy it then change the copy. change this... var deck_minus_player1 = pop_array(2,deck); to this... var deck_minus_player1 = deck; pop_array(2, deck_minus_player1); Quote Link to comment Share on other sites More sharing options...
drayarms Posted June 14, 2012 Author Share Posted June 14, 2012 @chrisdburns, quite interesting. I hadn't thought of it that way. I had earlier solved the problem like this var new_deck = concat(deck); //Assigning the deck array to a new array called new_deck since deck is about to be modified var deck_minus_player1 = pop_array(2,deck); Your method seems cleaner though. I'm gonna try it. Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.