简体   繁体   中英

Array.push modify existing elements

I am working on a small personal project and I ran over something that I don't understand and I am hoping if someone can explain it to me. One of the methods in my module is SaveSet() which takes an array and adds it to a different array as an element so it become two dimensional array here is the code for the SaveSet():

function SaveSet() {
    anim.push(set)
}  

When I run this code I expect it to take whatever is in the set array and adds it to the anim array as an element like this.

Set = [1,2,3,4]
SaveSet()
Set = [3,4,5,6]
SaveSet()

and I should end up with something like this:

[
   [1,2,3,4]
   [3,4,5,6]
]

However, my SaveSet() is modifying the existing one and adding a new one so I end up with something like this

[
  [1,2,3,4,3,4,5,6]
  [1,2,3,4,3,4,5,6]
]

I found a work around it by changing my SaveSet() to this:

function SaveSet() {
    let temp = JSON.stringify(set)
    anim.push(JSON.parse(temp));
}  

However, I still can't understand why anim.push is modifying the existing one as well. This is the full code incase if anyone wants to look at it. As I said this a personal quick project so the quality of the code and design are really low. https://codepen.io/anon/pen/oJZeJy?editors=1111

You are always using the same array for all of your data.

What is happening is that you're initializing a set = [] once globally in your code.

Then each time you save a set, you are adding this array into the anim array but you never update what the variable set is pointing to.

So you just keep adding the same set array over and over:

 var set = []; var anim = []; function addToSet() { set.push(String(Math.random()).slice(2,3)); console.log(set); } function saveSet() { anim.push(set); // <--- you are always pushing the same array console.log(anim); } 
 <button id="add" onclick="addToSet()">Add to set</button> <button id="save" onclick="saveSet()">Save set</button> 

Each time you save a set you should create a new set:

function saveSet() {
  anim.push(set);
  set = []; // <---- reset the set to a new array
}

With using .push method, you are pushing a pointer into your array. If you change your code to

function SaveSet() {
    anim.push([...set])
}  

it'll create a new array, spread current elements of set and push them to anim.

Your set array is probably changed because of a bug in another part of the code. It's not related to here

You should do the following :

var anim = []
function SaveSet(set){
  anim.push(set);
}
var set = [1,2,3,4];
SaveSet(set);
set = [3,4,5,6];
SaveSet(set);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM