简体   繁体   English

AS3 SharedObject怪异的数组纠缠

[英]AS3 SharedObject spooky array entanglement

var so:SharedObject = SharedObject.getLocal("example");
var arr:Array=[1,2,3];
so.data.arr = arr;
so.flush();
trace(so.data.arr); // outputs 1,2,3
arr[2]=5;
trace(so.data.arr); // outputs 1,2,5

As you see, I updated only arr , but so.data.arr got updated as well. 如您所见,我仅更新了arr ,但是so.data.arr也进行了更新。

so.data.arr doesn't update if instead of arr[2]=5; 如果不是arr [2] = 5,则so.data.arr不会更新; i write arr=[1,2,5]; 我写arr = [1,2,5];

Seems that arr and so.data.arr are linked somehow, but only if I update an element in the arr, not set the whole arr differently. 似乎arrso.data.arr是以某种方式链接的,但是仅当我更新arr中的元素时,才以不同的方式设置整个arr。

I discovered this accidentally. 我是偶然发现的。 Why is it working like that? 为什么这样工作?

Can I count that it works like that every time and use it? 我能指望它每次都能如此工作并使用吗? Thanks. 谢谢。

Basically speaking arrays are passed by reference, not by value. 基本上来说,数组是通过引用而不是通过值传递的。 That means if you assign an array variable to another one you are not creating a new array. 这意味着,如果将一个数组变量分配给另一个变量,则不会创建新的数组。

so.data.arr = arr;

means that both so.data.arr and arr point to the same array object. 表示so.data.arrarr指向同一数组对象。 That's why modifications to either one will be reflected by the other. 这就是为什么对任何一个的修改都会被另一个反映的原因。 They are pointing at the same thing. 他们指的是同一件事。 But

arr=[1,2,5];

will make arr point to some other array object, remember that [1,2,5] is a short hand version of new Array(1,2,5) . 将使arr指向其他数组对象,请记住[1,2,5]new Array(1,2,5)版本。

That's why after that line they aren't "linked" any more. 这就是为什么在该行之后,它们不再“链接”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM