Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    May 2013
    Posts
    45
    Thanks
    10
    Thanked 0 Times in 0 Posts

    How is this even possible?

    Code:
    var a = [[]];;
    var b;
    			
    a[0] = [1];
    b = a[0];
    			
    alert(a[0][0]);		//Displays 1
    			
    b[0] = 0;
    			
    alert(a[0][0]);		//Displays 0
    Basically, by changing the variable b, it affects the variable a. Is this supposed to happen?
    Anyway, is there a way to counter that? I want a[0][0] to remain the same no matter what I do with b.

  • #2
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    If you are aware of "Pass by Value" and "Pass by Reference" concept, same has been applied here.
    For, b= a[0], reference of a[0] is assigned to variable b.

    In order to avoid this, and to implement "Pass by Value", simply do following -

    Code:
    b = a[0].slice(); // this will create a new copy of array instance
    Regards,
    Niral Soni

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,292
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Quote Originally Posted by niralsoni View Post
    If you are aware of "Pass by Value" and "Pass by Reference" concept, same has been applied here.
    For, b= a[0], reference of a[0] is assigned to variable b.

    In order to avoid this, and to implement "Pass by Value", simply do following -

    Code:
    b = a[0].slice(); // this will create a new copy of array instance
    Regards,
    Niral Soni
    that doesn't pass by value, it just duplicates the array and passes a ref to the new array.

    note that this method also won't work if you have object elements in the array, since those will be passed byRef even when using slice() on the outer array.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

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