Flash 中的数组的关联

      :: Flash :: 2005-6-9 11:42
var array_ = new Array(1, 2, 3);
var str = array_;
trace(str);
trace(array_);
str.push(4);
trace(str);
trace(array_);
str.reverse();
trace(str);
trace(array_);

输出为:
1,2,3
1,2,3
1,2,3,4
1,2,3,4
4,3,2,1
4,3,2,1

数组变量很像c语言..中的指针,这应该算是 flash 中的一个 bug..

看到了解决方法,思路是逐一复制:
----------------------------------------------------------------------------------------
来自闪吧

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);
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}