www.webdeveloper.com
Results 1 to 5 of 5

Thread: Reverse array confusion

  1. #1
    Join Date
    Jun 2011
    Posts
    1

    Reverse array confusion

    Hi All,

    I have a very strange confusion which i am i am not able to understand. The issue is as below:
    Output of following code is: col, up, dl, ny
    HTML Code:
    <script type="text/javascript">
    
    var city = ["ny", "dl", "up", "col"];
    document.write(city .reverse());
    
    </script>
    Now, the output of the following code is the same: col, up, dl, ny

    HTML Code:
    <script type="text/javascript">
    
    var city = ["ny", "dl", "up", "col"];
    var newCity = city;
    newCity.reverse()
    document.write(city);
    
    </script>
    Why is variable city reversed in this case?

    Can anyone explain please? This is the first time i encountered this.

    You can try it here: http://www.w3schools.com/jsref/tryit...yjsref_reverse

    Thanks in advance,
    Vikram

  2. #2
    Join Date
    Aug 2007
    Posts
    3,767
    It's to do with the fact it's an object. newCity actually refers to the same object in memory as city does, so changing one is identical to changing the other.
    A better explanation.
    Great wit and madness are near allied, and fine a line their bounds divide.

  3. #3
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    declan explains half the effect: the part about all objects in js are passed byRef.

    the other trick is that Array.reverse is mutative, which means that it actually alters the Array it's called on. splice(), sort(), and the stack operators like push/pop also mutate.

    many array methods dont: map(), filter(), slice(), join(), etc all leave the orig intact.

    if you want another copy to reverse: newCity = city.slice().reverse()

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,377

    Lightbulb

    Would .concat() work just as well?
    Code:
    <script type="text/javascript">
    
    var city = ["ny", "dl", "up", "col"];
    var newCity = [].concat(city);
    newCity.reverse()
    document.write(city);
    document.write('<p>');
    document.write(newCity);
    
    </script>
    Leaves original untouched and a new array with reversed values.

  5. #5
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    i've found slice to bench slightly higher than concat in enough browsers to make it worth using slice(). plus, slice is one fewer key to press than concat...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles