2010-11-08 33 views
1

我不知道爲什麼下面的代碼不起作用。動作腳本 - 傳遞靜止類型強制失敗?

我只是傳遞,然後修復Shape對象作爲一個休息參數。當對象到達最終函數時,它們追蹤爲[對象形狀],但在下一行我收到類型強制失敗,說明它無法轉換爲形狀。

輸出:

[object Shape],[object Shape] 
TypeError: Error #1034: Type Coercion failed: cannot convert []@27b68921 to flash.display.Shape. 
    at Test/receiver() 
    at Test/passer() 
    at Test() 

代碼:

package 
{ 
import flash.display.Sprite; 
import flash.display.Shape; 

public class Test extends Sprite 
    { 
    public function Test() 
     { 
     //Create Shapes 
     var myFirstShape:Shape = new Shape(); 
     myFirstShape.graphics.beginFill(0); 
     myFirstShape.graphics.drawRoundRect(0, 0, 100, 100, 50); 

     var mySecondShape:Shape = new Shape(); 
     mySecondShape.graphics.beginFill(0); 
     mySecondShape.graphics.drawRoundRect(0, 0, 100, 100, 50); 

     //Pass Shapes 
     passer(myFirstShape, mySecondShape); 
     } 

    private function passer(...items):void 
     { 
     //Pass Shapes Again 
     receiver(items); 
     } 

    private function receiver(...items):void 
     { 
     //Rest Trace As [object Shape], [object Shape] 
     trace(items); 

     //Type Coercion Failed ??!! 
     for each (var element:Shape in items) 
        { 
        trace(element); 
        } 
     } 
    } 
} 

回答

1

這是一個位計數器第一眼直觀,但它實際上是有道理的......

在聲明其餘參數,實際傳遞的參數將在運行時包裝在數組中。

這意味着,如果你這樣做:

myFunction(1,2,3); 

你的函數將收到的磁盤陣列和3倍的值。

這正是這裏發生了:

private function passer(...items):void 
    { 
    //Pass Shapes Again 
    receiver(items); 
    } 

ìtems本身就是在passer身體的數組。但是當您調用receiver時,包含2個形狀的此數組將被包裝在另一個數組中,因爲您聲明receiver接受了一個休息參數。

當您在receiver中的循環嘗試將每個項目轉換爲形狀時,它會失敗(因爲您無法將Array轉換爲Shape)。

你可以看到這個改變你的代碼位:

private function receiver(...items):void 
    { 
    //Rest Trace As [object Shape], [object Shape] 
    trace(items); 
    trace(items.length);// --> traces 1 
    trace(items[0].length);// --> traces 2; this is the Array you want. 

} 

所以,你有幾個選項來解決這個問題,這取決於你真正想要達到的。

1)讓receiver「展開」其餘參數以獲取內部數組。基本上循環徹底items[0]而不是items

2)改變你函數簽名:

private function receiver(items:Array):void 

3)改變這樣的數組作爲參數列表中通過調用接收器的方式:

private function passer(...items):void 
    { 
    //Pass Shapes Again 
    receiver.apply(this,items); 
    } 

這樣做的效果會相當於這樣做:

receiver(items[0],items[1]); 

除了它動態地處理項目列表,當然。

如果你真的需要passer來取一個休息參數,你可以選擇3)。否則,我會選擇選項2)。選項1)是我最不喜歡的一個,因爲它是最脆弱的,但它也是一個有效的選項。

+0

這是輝煌的。非常感謝! – TheDarkIn1978 2010-11-09 04:45:17