首先要明确一点。数组的深复制浅复制是针对,数组里边有包含复杂数据类型的数据(可以理解为引用类型的数据,似乎也不能这么说。)如果数组里边全是基元数据,数组的深复制,浅复制所达到的效果是一样的。
还有,要注意一点。就是赋值。我们用“=”。只要是数组的赋值,只要一个数组的引用变了,另外一个也跟着改变了。不管数组里边的数据类型是什么样子的。这点和数组的深复制浅复制是不一样的。
数组的深复制用到ByteArray,浅复制用concat,slice。
下边贴出demo。点击按钮,分别测试数组的深复制,赋值,浅复制,浅复制。复杂数据类型仅用Array表示。
AS3 CODE:
package { import flash.display.Sprite; import flash.utils.ByteArray; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFieldType; public class Main extends Sprite { private var sp:Sprite; private var copyType:int = 1; private var shallowTyp:int = 1; private var txt:TextField=new TextField(); private var arrMoon:Array; private var arrSun:Array; private var arrIn:Array; public function Main():void { sp=new Sprite(); with (sp) { graphics.beginFill(0xff0000,0.3); graphics.drawRect(0,0,72,22); graphics.endFill(); } addChild(sp); sp.x = stage.stageWidth - sp.width * 2; sp.y = stage.stageHeight / 2 - sp.height / 2; sp.buttonMode = true; sp.addEventListener(MouseEvent.CLICK,clickHandler); txt.x = 50; txt.y = sp.height; txt.wordWrap = true; txt.multiline = true; txt.textColor=0xff0000; txt.type = TextFieldType.INPUT; txt.width = stage.stageWidth - 200; txt.height = stage.stageHeight - sp.height * 2; addChild(txt); } private function PutInfo(str) { trace(str); txt.appendText(str+"\n"); } private function clearTxt() { txt.text=""; PutInfo("******新的一轮将开始******"); } private function clickHandler(e:MouseEvent) { arrMoon = []; arrSun = []; arrIn = [0,1,2]; switch (copyType) { case 1 : clearTxt(); PutInfo("*********下边是深复制*********"); deepCopy(); break; default : PutInfo("*********下边是浅复制*********"); shallowCopy(); break; } copyType++; if (copyType>4) { copyType = 1; } } private function deepCopy() { arrMoon = ["月亮",arrIn]; var baObj:ByteArray=new ByteArray(); baObj.writeObject(arrMoon); baObj.position = 0; arrSun = baObj.readObject() as Array; PutInfo(arrMoon); PutInfo(arrSun); arrSun[0] = "太阳"; arrSun[1][0] = 9158; PutInfo(arrMoon); PutInfo(arrSun); } private function shallowCopy() { arrMoon = ["月亮",arrIn]; switch (shallowTyp) { case 1 : arrSun = arrMoon; break; case 2 : arrSun = arrMoon.slice(); break; case 3 : arrSun = arrMoon.concat(); break; default : break; } PutInfo(arrMoon); PutInfo("arrSun"+shallowTyp+"***:"+arrSun); arrSun[0] = "太阳"; arrSun[1][0] = 1314; PutInfo(arrMoon); PutInfo(arrSun); shallowTyp++; if (shallowTyp>3) { shallowTyp = 1; } } } }