简体   繁体   English

我数组中的每个元素都被最后一个元素推入覆盖

[英]Each element in my array gets overwritten by last element push in

Here is a fiddle : https://jsfiddle.net/reko91/998woow6/ 这是一个小提琴: 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. 按下AddToArray按钮,这会将nodesedges推入对象,然后将该对象推入thisArray数组。

  • Then click either DeleteNodes or DeleteEdges which pop the last element from either the nodes or edges arrays. 然后单击DeleteNodesDeleteEdges ,它们从nodesedges数组中弹出最后一个元素。

  • 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. 然后再次按AddToArray将更新的nodesedges推入对象,然后推入thisArray数组,您会注意到原始对象(索引为0的对象)被刚刚推入的对象覆盖。

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: 这是因为您要添加对数组的引用,因此每个对象都具有对同一数组的引用,请尝试使用slice克隆该数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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