推荐的方法从math-crunching AS3函数返回多个变量?

ggk*_*ath 3 apache-flex actionscript

我是Actionscript编程的新手.我试图弄清楚从函数返回多个变量的最佳方法是什么,每个变量都有不同的数据类型.例如,如果函数需要返回变量aa(字符串)和变量bb(数字).

我正在使用的函数只是处理大量的数学运算,并且与GUI中的对象无关.我从Google搜索获得的一种方法使用了一个Object,但是(我认为)这需要我创建一个类,我想知道是否有更简单的方法.由于数组可以包含不同数据类型的元素,因此这可能是一种更简单的方法(?).

以下是David Gassner从"Flash Builder 4和Flex 4 Bible"中获取的mxml和AS3文件示例.

文件:Calculator.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark" 
  xmlns:mx="library://ns.adobe.com/flex/mx" 
  xmlns:components="components.*">
  <fx:Script source="calculator.as"/>
  <s:Panel title="Calculator" horizontalCenter="0" top="20">
    <s:layout>
      <s:VerticalLayout horizontalAlign="center"/>
    </s:layout>
    <mx:Form>
      <components:ButtonTile id="input" 
        select="selectHandler(event)" 
        calculate="calculateHandler(event)"/>
      <mx:FormItem label="Entry:">
        <s:TextInput text="{currentInput}" editable="false" width="80"/>
      </mx:FormItem>
      <mx:FormItem label="Total:">
        <s:TextInput text="{currentResult}" editable="false" width="80"/>
      </mx:FormItem>   
    </mx:Form>
Run Code Online (Sandbox Code Playgroud)

file:calculator.as

//ActionScript code for Calculator.mxml
[Bindable]
private var currentResult:Number=0;
[Bindable]
private var currentInput:String="";

private function calculateHandler(event:Event):void
{
  currentResult += Number(currentInput);
  currentInput="";
}
private function selectHandler(event:TextEvent):void
{
  currentInput += event.text;
}
Run Code Online (Sandbox Code Playgroud)

有人可以说明如何修改calculator.as中的一个函数,作为一个例子,如何返回两个值,其中一个是数字而另一个是字符串?是否有明显的最佳方式来实现这一目标,或者,不同方法的优点/缺点是什么?提前致谢!

Mar*_*rty 8

你可以简单地返回一个Object,dynamic因此可以动态定义值,如下所示:

return {something: "string", another: 18};
Run Code Online (Sandbox Code Playgroud)

要么:

var obj:Object = {};

obj.something = "string";
obj.another = 18;

return obj;
Run Code Online (Sandbox Code Playgroud)

但在我看来,这实际上是很糟糕的做法(特别是如果你的功能是用新值返回相同的信息集).

我采取这条路线:

您可以创建自己的类,其中包含各种属性.从那里,您可以返回此对象的实例,并根据需要定义属性.

示例:
这将在一个名为的外部文件中CollisionData.as

package
{
    public class CollisionData
    {
        public var x:Number = 0;       // X coordinate of the collision
        public var y:Number = 0;       // Y coordinate of the collision
        public var angle:Number = 0;   // Collision angle
    }
}
Run Code Online (Sandbox Code Playgroud)

你的功能可能是:

function calculate():CollisionData
{
    var col:CollisionData = new CollisionData();

    // determine collision details
    col.x = 115;
    col.y = 62;
    col.angle = 0.345;

    return col;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据结果创建自己的碰撞数据:

var myCollision:CollisionData = calculate();
Run Code Online (Sandbox Code Playgroud)

并获取详细信息:

trace(
    myCollision.x,
    myCollision.y,
    myCollision.angle
);
Run Code Online (Sandbox Code Playgroud)