2 Replies Latest reply on Sep 10, 2009 3:27 AM by christoferek

    An easy Array question

    christoferek Level 1

      Hi All,

       

      I spoted something strange in this code.

       

              var tempArr:Array = new Array();

              var temp1:Array = new Array(null, null, null);
              var temp2:Array = new Array(null, null, null);
              var temp3:Array = new Array(null, null, null);
              var temp4:Array = new Array(null, null, new Array());
             
              tempArr[0] = new Array(1, temp1, temp2, temp3, temp4);
              tempArr[1] = new Array(1, temp1, temp2, temp3, temp4);
              tempArr[2] = new Array(1, temp1, temp2, temp3, temp4);
              tempArr[3] = new Array(1, temp1, temp2, temp3, temp4);
             
              tempArr[1][4][3] = 55;

       

      The last line should change only one cell [1][4][3] to 55 but it changed also  [0][4][3],  [1][4][3],  [2][4][3], [3][4][3] all to 55.

       

      What am I doing wrong?

       

      Can you help?

       

      Christoferek

        • 1. Re: An easy Array question
          _Natasha_ Level 4

          Hi,

           

          "The last line should change only one cell [1][4][3] to 55 but it changed also  [0][4][3],  [1][4][3],  [2][4][3], [3][4][3] all to 55." - This is correct!

           

          Your tempArr is different objects, but all contain the same objects.

          Then you create an array with objects, not a copy of objects putted to array. A link to this object is putted there.

          So...

          you write

          tempArr[1][4][3] = 55;

          means...

          tempArr[1][4] === temp4;

          tempArr[1][4][3] === temp4[3];

           

          temp4 - is an object in tempArr[0] - tempArr[3].

          So then you change an object in temp4[i] also tempArr[0-3][4][i] is changed.

           

          So

          tempArr[1][4][3] = 55;

          equivalent

          temp4[3] = 55;

           

          If you want to have a different objects (copy of objects), use ObjectUtil.copy(...)

          • 2. Re: An easy Array question
            christoferek Level 1

            Thank you. This is it. I've made a mistake and coudn't find it.

             

            Regards

             

            Chris