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
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()
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.