我需要一些帮助。我是动作脚本的新手,我想要做的是从数组中计算苹果的数量,然后在主函数中跟踪它。现在我收到了返回错误,错误是 1067:将String类型的值隐式强制转换为不相关的类型数。现在我试图切换数字和字符串,但我仍然得到错误。
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;
}
}
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
该错误是因为您尝试返回total
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;
}