简体   繁体   中英

Each element in my array gets overwritten by last element push in

Here is a fiddle : https://jsfiddle.net/reko91/998woow6/

It is a basic version of a part in my project. Basically, as the question says, when I push an element into my array, every other element already in the array gets overwritten by the last element pushed in.

To rein act the problem :

  • Press the AddToArray button, this pushes the nodes and edges in to an object and then pushes this object in to the thisArray array.

  • Then click either DeleteNodes or DeleteEdges which pop the last element from either the nodes or edges arrays.

  • Then press AddToArray again to push the updated nodes and edges into an object, then into the thisArray array and you'll notice that the original object, the object at index 0, is overwritten by the object just pushed in.

I've tried looking online, it must have something to do with closures, but I'm not having any luck figuring this one out.

Here is the code if it's easier to view here :

 var thisArray = []; var nodes = [1, 2, 3, 4, 5]; var edges = [1, 2, 3, 4, 5]; function addToArray() { var thisData = { nodes: nodes, edges: edges } thisArray.push(thisData) console.log('thisArray') console.log(thisArray) } function deleteNodes() { nodes.pop(); console.log(nodes) } function deleteEdges() { edges.pop(); console.log(edges) } 
 <button onclick='addToArray()'> AddToArray </button> <button onclick='deleteNodes()'> Delete Nodes </button> <button onclick='deleteEdges()'> Delete Edges </button> 

It's because you're adding reference to an array so each object have the reference to the same array, try to clone the array using slice:

function addToArray() {
  var thisData = {
    nodes: nodes.slice(),
    edges: edges.slice()
  }
  thisArray.push(thisData)
  console.log('thisArray')
  console.log(thisArray)
}

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