0

我需要一些帮助。我对actionscript很陌生,我想做的是从数组中计算苹果的数量,然后在主函数中跟踪它。现在我在返回时遇到错误,该错误是1067: Implicit coercion of a value of type of String to an unrelated type Number。现在我试图切换数字和字符串,但我仍然得到错误。

public class extends Sprite
{

    public function()
    {
        var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
        var totalApples:Number = countingApples(fruitNames);
        trace("You have " + totalApples);
    }

    private function countingApples(fruitNames:Array):Number
    {
        var total:String = "apple";

        for(var i:uint=0; i<7; i++)
        {
            total += Number[i];

        }
        return total;
    }

}
4

2 回答 2

0
public class extends Sprite
{

    public function()
    {
        var fruitNames:Array = ["apple", "peach","banana","pear","guava","apple","peach"];
        var totalApples:Number = countingApples(fruitNames);
        trace("You have " + totalApples);
    }

    private function countingApples(fruitNames:Array):Number
    {
        var total:uint = 0;

        var i:String = new String();
        for(i in fruitNames) {
            if (fruitNames[i] == "apple") {
                total = total + 1;
            }
        }
        return total;
    }

}
于 2013-03-22T22:14:25.710 回答
0

该错误是因为您尝试返回total,这是 a String,但您已将countingApples函数的返回类型设置为Number。这是一个可以满足您要求的示例,但我认为您应该再次尝试编写自己的版本,以便了解发生了什么:

private function countingApples(fruitNames:Array):Number
{
    var total:uint = 0;
    var targetFruit:String = "apple";
    var totalFruit:uint = fruitNames.length;

    for(var i:uint = 0; i < totalFruit; i++)
    {
        if (fruitNames[i] == targetFruit) {
            total++;
        }
    }

    return total;
}
于 2013-03-22T22:15:26.370 回答