Skip to main content
Anonymous507
Known Participant
April 5, 2013
質問

Array manipulation

  • April 5, 2013
  • 返信数 2.
  • 694 ビュー

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


このトピックへの返信は締め切られました。

返信数 2

April 7, 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;

Anonymous507
Anonymous507作成者
Known Participant
April 10, 2013

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

Nabren
Inspiring
April 5, 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);

}