SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    Posts
    387
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Changing One Array Also Changes Another

    This is a simplified version of the problem I'm having:

    Code JavaScript:
    var a = ["Pikachu", "Bulbasaur", "Charmander", "Squirtle"],
    b = a,
    c = a;
     
    alert(b.length);    // Alerts "4"
    c.splice(0, 1);
    alert(b.length);    // Alerts "3"

    How do I initialize b and c so that what I do to one doesn't affect the other?

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by sdleihssirhc View Post

    How do I initialize b and c so that what I do to one doesn't affect the other?
    Provided that none of the elements are types that are passed by reference:
    Code:
    var a = ["Pikachu", "Bulbasaur", "Charmander", "Squirtle"],
    
    b = a.slice( 0 ),
    c = a.slice( 0 );
    
    // or
    
    b = [].concat( a );
    c = [].concat( a );
    Tab-indentation is a crime against humanity.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •