Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   Непонятнео поведение переменных типа Array вариант Object (http://www.flasher.ru/forum/showthread.php?t=108159)

†‡Paladin‡† 16.02.2008 15:44

Непонятнео поведение переменных типа Array вариант Object
 
Приветствую. Думаю сразу выложу код, так будет показательней. Код на флексе, но проблема чисто as3.
Код:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
        <mx:Script>
                <![CDATA[
                        import mx.controls.Alert;
               
                        private var _myObj:Array = [ 1, 2, 3, 4, 5];
                        private var _myObj2:Array = [ 1, 2, 3, 4, 5];                       
               
                        [Bindable]
                        private var myCollection:Array = new Array();
               
                        private function onClick(e:Event):void {
                                dispatchEvent(new Event('testEvent', true, true));
                        }
                        private function onClick2(e:Event):void {
                                var newItem:Array = new Array();
                                newItem = _myObj2;
                                newItem.push('qwerty');
                                trace(_myObj2.toString());
                        }       
                                       
                        private function init():void {
                                this.addEventListener('testEvent', onTestEvent);
                        }
                       
                        private function onTestEvent(e:Event):void {
                                var newItem:Array = new Array();
                                newItem = _myObj;
                                newItem.push('qwerty');
                                myCollection.push(newItem);
                                MyList.dataProvider = myCollection;
                                for (var i:int = 0; i < myCollection.length; i++) {
                                        trace(i + ": " + myCollection[i]);
                                }
                        }
                ]]>
        </mx:Script>
        <mx:List x="504" y="10" width="270" height="455" dataProvider="{myCollection}" id="MyList"></mx:List>
        <mx:Button x="10" y="10" label="Add item" click="onClick(event)"/>
        <mx:Button x="96" y="10" label="Add Item2" click="onClick2(event)"/>
       
</mx:Application>

Объясните мне пожалуйста почему newItem.push('qwerty');
затрагивает _myObj и как этого избежать.

†‡Paladin‡† 16.02.2008 16:20

Вобщим с помощью мозга Mr.Fixit`а проблема решилась. Оказывается просто так копирнуть массив нельзя. Необходимо использовать функцию concat() без параметров.
А моя проблема была описана в справке мелким шрифтом гдето в конце абзаца.
Цитата:

Cloning arrays
The Array class has no built-in method for making copies of arrays. You can create a shallow copy of an array by calling either the concat() or slice() methods with no arguments. In a shallow copy, if the original array has elements that are objects, only the references to the objects are copied rather than the objects themselves. The copy points to the same objects as the original does. Any changes made to the objects are reflected in both arrays.
Для объектов еще интересней. Необходимо использовать аш ByteArray(!).
Функция из справки:
Код:

function clone(source:Object):*
{
    var myBA:ByteArray = new ByteArray();
    myBA.writeObject(source);
    myBA.position = 0;
    return(myBA.readObject());
}

Желаю всем читать матчать внимательней, т.к. у меня на решение проблемы ушло 2е суток =\


Часовой пояс GMT +4, время: 05:56.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.