[Flash] 修正多维数组复制的问题

作者:Super-Tomato
原文:http://www2.flash8.net/teach/2913.htm

不知道可否有人试过复制多维数组变量后,修改原来的数组变量,而拷贝的变量值也一起更换呢?

如:

var myArray:Array = new Array([1,2]); 
var temp:Array = myArray; 
myArray[0][0] = 3; 
trace(myArray); //3,2 
trace(temp); //没更动但却输出3,2

而经过测试之后,在一维数组却没有问题。所以从此处写出修正的方法

Array.prototype.duplicate = function(){ 
var a = []; 
for (var i in this) (this[i] instanceof Array) ? a[i] = this[i].slice() : a[i] = this[i]; 
return a; 
} 
var myArray:Array = new Array(); 
myArray[0]=[1,2] 
myArray[1]=3 
myArray[2]=[5,6] 
var temp:Array = myArray.duplicate(); 
trace(myArray); //1,2,3,5,6 
trace(temp); //1,2,3,5,6 
myArray[0][0] = 5; 
trace(myArray); //5,2,3,5,6 
trace(temp); //1,2,3,5,6加了个object的判断
Object.prototype.duplicate = function() { //我想应该没有人会在object中建立object了吧
var b = new Object();
for (var j in this) {
b[j] = this[j];
}
return b;
};
Array.prototype.duplicate = function() {
var repetition:Array = new Array();
for (var element in this) {
if (this[element] instanceof Array) {
repetition[element] = this[element].duplicate();
} else if (this[element] instanceof Object) {
repetition[element] = this[element].duplicate();
} else {
if (!(this[element] instanceof Function)) {
repetition[element] = this[element];
}
}
}
return repetition;
};
var myArray:Array = new Array();
myArray[0] = [1, 2];
myArray[1] = {x:3, y:4};
myArray[2] = [5, [6, {a:21, b:22}]];
var temp:Array = myArray.duplicate();
trace(myArray[2][1][1].a);
trace(temp[2][1][1].a);
myArray[2][1][1].a = 8;
trace(myArray[2][1][1].a);
trace(temp[2][1][1].a);

除了object中建立object外,这个写法一次解决了Array和Object的复制问题,我想应该没有什么遗漏了吧

谢谢分享哦 Y^^