ActionScript3:如何在声明对象后初始化对象中的数组长度?

时间:2012-02-24 04:14:25

标签: actionscript

我使用的是AS3类:

package {
    public class PeopleInfo {
        public var elements:int;
        public var PeopleName:Array;
        public var PeopleInt:Array;
        public var PeopleDecimal:Array;
    }
}

在另一个文件中我有:

<?xml version="1.0" encoding="utf-8"?>
<s:Application 
    creationComplete="initApp()"
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[
        public var ii:int;  

        public var dataWriteToDB:PeopleInfo = new PeopleInfo;

        public function initApp():void
        {
            // Initialize data provider array.

            var int_data:Array = new Array(10, 20, 30, 40, 50);
            var decimal_data:Array = new Array(13.11, 23.34, 35.69, 43.29, 58.92);
            var name:Array = new Array("Joe", "Karen", "Simon", "Greg", "Alice");

            dataWriteToDB.elements = 5; // number of elements in array

            for (ii = 0; ii < dataWriteToDB.elements; ii++)
            {
                dataWriteToDB.PeopleName[ii] = name[ii];
                dataWriteToDB.PeopleInt[ii] = int_data[ii];
                dataWriteToDB.PeopleDecimal[ii] = decimal_data[ii];
            } 

        }
and so on...

我遇到运行时错误:Error #1009: Cannot access a property of method of a null object reference引用for循环的第一行dataWriteToDB.PeopleName,因为它是NULL。

我猜这里的问题是,虽然最初声明了dataWriteToDB,但还没有设置PeopleInfo类中数组的数组长度。或者,不确定为什么它是NULL。任何人都知道如何清除它?

1 个答案:

答案 0 :(得分:1)

数组尚未在类中初始化。你应该在声明中这样做:

package {
    public class PeopleInfo {
        public var elements:int;
        public var PeopleName:Array = [];
        public var PeopleInt:Array = [];
        public var PeopleDecimal:Array = [];
    }
}

还考虑使用push向数组中添加元素,以避免意外访问不存在的索引:

        for (ii = 0; ii < dataWriteToDB.elements; ii++)
        {
            dataWriteToDB.PeopleName.push(name[ii]);
            dataWriteToDB.PeopleInt.push(int_data[ii]);
            dataWriteToDB.PeopleDecimal.push(decimal_data[ii]);
        }