【问题标题】:AS3 - Why is the class array not working properly?AS3 - 为什么类数组不能正常工作?
【发布时间】:2014-08-27 03:34:24
【问题描述】:

我有一个名为 tOne 的课程。课程代码如下。

public class tOne extends MovieClip {
    private var _root:MovieClip;
    public var tPath:Array = new Array();

    public var index:int = 0;       

    public function tOne() {
        this.addEventListener(Event.ADDED, beginClass);
        this.addEventListener(Event.ENTER_FRAME, gameLoop);
    }

    private function beginClass(e:Event):void {
        _root = MovieClip(root);            
        tPath = _root.tMovingPath; //Sets the tPath array to a bunch of coordinates
    }

    private function gameLoop(e:Event):void {
        if (tPath[index] != null) {             
            this.x = tPath[index].xCoord;
            this.y = tPath[index].yCoord;
            tPath.splice(index, 1); //Here is the problem

            index++;
        }
    }
}

我创建了这个类的三个实例,所以我有 3 个 tOne 对象。现在我的问题是,当我使用 'tPath.splice(index, 1)' 时,它不会从 tOne 对象之一中删除该索引,而是从所有三个对象中删除。

因此,如果在 tOne 的第一个对象中我有一个长度为 3 的数组并删除其中一个,它会从 tOne 的其他两个对象中删除一个。

我不明白为什么。

谁能给我解释一下发生了什么?

【问题讨论】:

    标签: arrays actionscript-3 class object


    【解决方案1】:

    在你的队伍中

    tPath = _root.tMovingPath;
    

    您正在设置 tPath 以引用数组。所有三个对象的引用都会指向同一个数组。

    您需要做的是为该数组创建一个copy。一种方法:

    tPath = _root.tMovingPath.concat();
    

    【讨论】:

    • 效果很好。我一直认为,如果您将一个数组设置为另一个数组,则内容会被复制。我错了。无论如何,谢谢你。
    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2016-07-16
    • 2019-01-04
    • 2020-09-03
    • 2016-10-10
    • 2016-10-24
    • 2017-02-27
    相关资源
    最近更新 更多