Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Array manipulation

Community Beginner ,
Apr 05, 2013 Apr 05, 2013

Hi,

I like to know whether the array can be manipulated better than below code.

My game has buttons called ADD and UNDO . When I press ADD it will create some shapes as movieclip, which will be saved in an array for undo. UNDO button is to remove the created shapes in the order it was created.

For this, whenever shape was created ill push them in an array. For UNDO ill pop () the array and remove them. 

Now I need to add a new button called DELETE, which will remove the selected shapes. For that I have added the below code, it works fine.  I like know without this loop can I delete

below is my code,

Var shapeArr:Array = new Array();

ADD :

  1. shapeArr.push(myMc);

UNDO :

removeChild(shapeArr.pop())

for DELETE:

shapeArr.reverse();

for (var i=0; i< shapeArr.length; i++)

{

                If(shapeArr.name == removeMc.name){

                                shapeArr.splice(i,1);

}             

}

shapeArr.reverse();

thanks in advance


TOPICS
ActionScript
660
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Apr 05, 2013 Apr 05, 2013

That loop solution is fine but why do you feel the need to reverse the array both before and after? It has no impact on your logic especially because you call reverse twice so it will end up in the same order it was to begin with minus the deleted item. You could take out the calls to .reverse() and nothing would change with the functionality.

The only way to do it without a loop would be this:

var shapeIdx:int = shapeArr.indexOf(removeMc);

if (shapeIdx >= 0)

{

     shapeArr.splice(shapeIdx, 1);

}

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guest
Apr 07, 2013 Apr 07, 2013

Nabren is right, the reverse is silly - if you wanted a for loop just iterate backwards. The indexOf is better though - and for fun you could even do it in a one liner:

shapeArr.indexOf(removeMc) != -1 ? shapeArr.splice(shapeArr.indexOf(removeMc),1) : -1;

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Beginner ,
Apr 10, 2013 Apr 10, 2013
LATEST

Thanks for reply. i have corrected my silly mistake(reverse)

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines