Nabi Nabi - 1 year ago 88
Javascript Question

Javascript variable fix last value after changes

This is my training:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
var fruits2 = fruits;
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
my first variable (fruits) also will changed,

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

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download