1

This is my training:

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits;
    
    function myFunction() {
        var fruits2 = fruits;
        fruits2.reverse();
        document.getElementById("demo").innerHTML = fruits+'<br>'+fruits2;
    }
<p>Click the button to reverse only last array (fruits2).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

When i reverse fruits2 my first variable (fruits) also will changed,

I only don't want it so! I think must be easy

Nabi
  • 764
  • 1
  • 10
  • 22

2 Answers2

4

fruits2 = fruits says fruits2 is now the same object - not a copy of fruits, but the same object as fruits.

It's like giving your friend Harry a nickname, say Maddog. When you punch Maddog, Harry gets angry as well. They're not two separate people, they're one person with two ways of referring to him.

You need to clone your array if you want to keep them separate. Easiest to make a copy of an array is using slice:

 var fruits2 = fruits.slice()
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

That is because your fruits and fruits2 are same array. When you reverse one the second one also get reversed.

You need to make another copy of your array. One easy way is

var fruits2 = JSON.parse(JSON.stringify(fruits));

Or

var fruits2 = fruits.slice()

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits;
    
    function myFunction() {
        var fruits2 = fruits.slice()
        fruits2.reverse();
        document.getElementById("demo").innerHTML = fruits+'<br>'+fruits2;
    }
<p>Click the button to reverse only last array (fruits2).</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • 2
    Note that `JSON.parse(JSON.stringify(...))` trick only works if the array is fully and reversibly serialisable. There is no advantage in using it over `slice`. – Amadan Nov 07 '16 at 02:31
  • I agree to that, it's just one way which I use when needed. I never felt it has an advantage. The idea for OP was to copy the array somehow. – Mritunjay Nov 07 '16 at 02:33