extending AS3's Array access operators to 'wrap' out-of-bound index values

痴心易碎 提交于 2019-11-30 07:44:24

Check out the Proxy class: http://livedocs.adobe.com/flex/2/langref/flash/utils/Proxy.html.

I haven't used it myself but it seems it could do the job. I modified the sample code in the docs and it works the way you want. I haven't thoroughly tested it, though, and you might want to do it. Personally, I would not extend Array and just make a simple class with 2 methods for adding/retrieving, since the proxy idea seems a bit involved to me. But that's me.

package
{
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    dynamic class ProxyArray extends Proxy {
        private var _item:Array;

        public function ProxyArray() {
            _item = new Array();
        }

        override flash_proxy function callProperty(methodName:*, ... args):* {
            var res:*;
            res = _item[methodName].apply(_item, args);
            return res;
        }

        override flash_proxy function getProperty(name:*):* {
            if(!isNaN(name)) {
                var index:int = name;
                while(index < 0) {
                    index += this.length;

                }
                return _item[index % this.length];
            }


            return _item[name];
        }

        override flash_proxy function setProperty(name:*, value:*):void {
            _item[name] = value;
        }
    }
}

Use:

        var a:ProxyArray = new ProxyArray();
        // you can't use this syntax ['a','b','c'], since it would return an Array object
        a.push("a");
        a.push("b");
        a.push("c");
        a.push("d");
        a.push("e");
        a.push("f");

        trace(a[-3]);
        trace(a[9]); 

Not really. You can not override the [] operator. However you can extend the Array and add a function that will apply the code snippet. That being said I am not sure why you really want this functionality. A circular linked list would be a more suitable data structure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!