开发者

AS3 Functions: is it possible to return a value inside of a loop?

开发者 https://www.devze.com 2022-12-19 06:40 出处:网络
I am trying to find the index from an array using a loop function, but I am getting an error: private function findMatch(matchValue:int):int {

I am trying to find the index from an array using a loop function, but I am getting an error:

private function findMatch(matchValue:int):int {
        for (var i:int = 0; i < playersList.length; i++) {
           if (playersList[i].value + matchValue == levelTarget) {
    开发者_如何学C                    return i;
                } 
                }
    }

Is it not possible to return a value from inside a loop, or rather, am I getting an error everytime it doesn't return a value?!?


private function findMatch(matchValue:int):int {
    var _i:int = -1;
    for (var i:int = 0; i < playersList.length; i++) {
       if (playersList[i].value + matchValue == levelTarget) {
                 _i = i;
                break;  
        } 
    }
    return _i;
}


You can return from anywhere in a function, but you have to satisfy all code paths with a return value. As described above, you'll need to return a "non-valid" value to indicate no index is found, which is commonly -1.


In many programming languages you can return from any point in a method. The compiler is probably complaining because it can't be sure that it will find the right value in the loop, and then will have nothing to return (even if you as the developer are convinced that it will return before exiting the loop).

So yeah, adding some default return at the end is the right thing to do, and -1 is a common default answer for this kind of thing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号