3 Replies Latest reply on Jun 28, 2016 12:15 AM by Heimdaal

    Array objects get overwritten

    Heimdaal Level 1

      I have a function that creates some custom objects and pushes these into an array.
      Problem is that during the loop, ALL objects in the array are replaced. Obviously it is some kind of mutability error, but I can't really see how I can fix it!

      function myFunc(layers){
      
      
          // Create objects of all layers
          var myNodes = [];
          for (var i in layers){
              activeDocument.activeLayer = layers[i];
              var myNode = MyNodeObj(layers[i]);
              alert("created node - pushing to myNodes-list. lyrName is: " + myNode.lyrName);
      
      
              // Works until this point
              myNodes.push(myNode);
          }
          for (var i in myNodes){
              alert("test " + myNodes[i].lyrName);
          }
      

       

      I send layers to the function and it goes through them, creating objects via MyNodeObj (class using a constructor). When the alert pops up, I can see that myNode.lyrName is different - it has the name of the active layer. However, once this object is pushed into the myNodes -array it will overwrite all objects inside it.

       

      So for three layers (called "object1", "object2" and "object3") the array will look like this on first entry:
      ["object1"]

      then

      ["object2", "object2"]

      and finally

      ["object3", "object3", "object3"]

       

      What is happening here?

       

      EDIT: Ok so objects are pushed to arrays as references - but for numbers they are pushed as a copy.
      Either way, I tried "disconnecting" the old object reference by declaring myNode as an empty object at the start, and then creating my object:
      var myNode = {};

      myNode = MyNodeObj(layers[i]);

       

      EDIT2:
      The below doesn't work either - so how is one supposed to fill an array with several generated objects?

       

      function myFunc(layers){
      
      
          // Create objects of all layers
          var myNodes = [];
          for (var i in layers){
              activeDocument.activeLayer = layers[i];
              myNodes.push( MyNodeObj(layers[i]) ); // Also doesn't work
              // Also tried this: myNodes[i] = MyNodeObj(layers[i]);
          }
          for (var i in myNodes){
              alert("test " + myNodes[i].lyrName);
          }
      

       

      MyNodeObj looks like:

      function MyNodeObj(layer){
      
      
          this.height = layer.bounds[3].value - layer.bounds[1].value;
          this.width = layer.bounds[2].value - layer.bounds[0].value;
          this.lyrName = layer.name;
      
      
          return this;
      }