开发者

AS3 Array question

 var firstarray:Array = new Array();


 function traceArray(arr:Array){    
  for(var i:int = 0; i < arr.length; ++i) {
       trace(firstarray[i].matrix);    
  } 
 }



 for (var i:int = 0; i < 10; ++i) {   
  firstarray.push({ matrix:[1,0,0,1], prod:i}); 
 }

 var secondarray:Array = new Array();
 secondarray = firstarray;
 secondarray.push({ matrix:"hello" });

 traceArray(开发者_如何学编程firstarray);

should the trace result be

1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1

1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1

1,0,0,1 1,0,0,1 hello

or

1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1

1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1

1,0,0,1 1,0,0,1


it will output:

1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
1,0,0,1
hello

This is because you are setting secondarray to the same array reference as firstarray.

If you want to copy the contents of firstarray into secondarray use concat():

secondarray = firstarray.concat();

Actually, since you are using arrays in an array, you might have to loop each element and concat copy the contents of each matrix item. (Sorry for the edits, but I just remembered. ;))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜