gpt4 book ai didi

actionscript-3 - actionscript 3 : how to pass array by reference to function, 并让该函数更新它?

转载 作者:行者123 更新时间:2023-12-04 08:27:28 25 4
gpt4 key购买 nike

默认情况下,ActionScript 3 通过引用传递数组。我一定是犯了一个新手错误。这是我的代码的快照:

private function testFunc():void {
var testArray:Array=new Array();
myFunction(testArray);
trace(testArray); // []; length=0
}

private function myFunction(tArray:Array):void {
tArray = myOtherFunction();
trace(tArray); // 0, 1, 2; length=3
}

private function myOtherFunction():Array {
var x:Array=new Array;
for (var i:int=0; i<3; i++)
x[i]=i;
return x;
}

我可以看到 tArray 是正确的,但是 testArray 总是空的。知道如何使 testArray 等于 tArray 吗?提前致谢。

http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000049.html

更新:

就其值(value)而言,我发现以下更改(hack)有效:

private function myFunction(tArray:Array):void {
var Z:Array=new Array;
Z = myOtherFunction();
for (var i:int=0; i<Z.length; i++)
tArray[i]=Z[i];
}

不过,Georgii 的解决方案是更好的设计。

最佳答案

当您将 testArray 作为参数传递给 myFunction 时,它的引用被复制并分配给本地引用 tArray,这样 myFunction 内部的 tArray 指向与 testArray 相同的对象,但实际上是不同的引用。这就是为什么当您更改 tArray 引用时,testArray 本身不会更改。

private function testFunc():void {
var testArray:Array=new Array();
// testArray is a local variable,
// its value is a reference to an Array object
myFunction(testArray);
trace(testArray); // []; length=0
}

private function myFunction(tArray:Array):void {
// tArray is a local variable, which value equals to testArray
tArray = myOtherFunction();
// now you changed it and tArray no longer points to the old array
// however testArray inside of testFunc stays the same
trace(tArray); // 0, 1, 2; length=3
}

你可能想要的是:

private function testFunc():void {
var testArray:Array=new Array();
testArray = myFunction(testArray);
trace(testArray); // 0, 1, 2; length=3
}

private function myFunction(tArray:Array):Array {
// do what you want with tArray
tArray = myOtherFunction();
trace(tArray); // 0, 1, 2; length=3
// return new value of the tArray
return tArray;
}

private function myOtherFunction():Array {
var x:Array=new Array;
for (var i:int=0; i<3; i++)
x[i]=i;
return x;
}

关于actionscript-3 - actionscript 3 : how to pass array by reference to function, 并让该函数更新它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14595987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com