.slice()是一个“浅层克隆”是什么意思?

时间:2011-02-23 16:08:34

标签: arrays actionscript vector slice shallow-copy

ActionScript的Array和Vector类都有slice()方法。如果未传递任何参数,则新的Array或Vector是原始Vector的重复(浅层克隆)。

成为“浅层克隆”意味着什么?具体来说,

之间有什么区别
Array newArray = oldArray.slice();
Vector.<Foo> newVector = oldVector.slice();

Array newArray = oldArray;
Vector.<Foo> newVector = oldVector;

?另外,如果Vector的基类型不是Foo,而是像int这样简单且不可变的东西呢?

更新

以下结果是什么?

var one:Vector.<String> = new Vector.<String>()

one.push("something");
one.push("something else");

var two:Vector.<String> = one.slice();

one.push("and another thing");

two.push("and the last thing");

trace(one); // something, something else, and another thing
trace(two); // something, something else, and the last thing

谢谢! ♥

1 个答案:

答案 0 :(得分:1)

在您的上下文中,.slice()所做的只是制作矢量副本,以便newArray引用与oldArray不同的对象,但两者看起来都是相同的对象。同样适用于newVectoroldVector

第二个片段:

Array newArray = oldArray;
Vector.<Foo> newVector = oldVector;

实际上将newArray 引用设为oldArray。这意味着两个变量都引用相同的数组。 newVectoroldVector相同 - 最终都指向相同的向量。可以把它想象成使用橡皮图章在不同的纸张上盖上相同的印章两次:它是相同的印章,只是用两张纸代表。

在旁注中,术语浅拷贝深拷贝不同,因为浅层是仅对象的副本,而深层是对象及其所有属性的副本

  

另外,如果Vector的基类型不是Foo,而是像int那样简单且不可变的东西怎么办?

它是相同的,因为你的变量是指Vector个对象而不是int个。

  

以下结果是什么?

您的输出是正确的:

something, something else, and another thing
something, something else, and the last thing

two = one.slice(),不带任何参数,制作one的新副本及其所有当前内容,并将其分配给two。当您将每个第三个项目推送到onetwo时,您将附加到不同的Vector个对象。