Skip to main content
January 3, 2013
Answered

Searching array question

  • January 3, 2013
  • 2 replies
  • 849 views

Hi

I'm using the following to search for the index of a nested array within the array 'folders', that contains an object whose id matches a certain value.  The objects being searched are at position 0 of each nested array.

function find(id):int

    for (var i:int = 0; i < folders.length; i++)

    {       

        if(folders[0].id == id) return i;

    }

}

find("my_value");

...gives me the error: function does not return a value

But if I get rid of the :int...

function find(id)

...it works.

It's definitely an integer returning, as I'm able to use it mathemtaically later.

Why does this happen?

Thanks

This topic has been closed for replies.
Correct answer Ned Murphy

Since the return of the i value is conditional it is possible the function will fail to return a value.  You should probably rearrange things so that the return happens outside of the loop, where in the case of no value matching you return a -1 or some other value that could not be related to an array index.

2 replies

esdebon
Inspiring
January 3, 2013

if  a function return a value then the function ever need return a value with condition or not

function find(id):int

var idx:int=-1;

    for (var i:int = 0; i < folders.length; i++)

    {       

        if(folders[0].id == id) idx=i;

    }

     return idx;

}

January 4, 2013

Thank you guys - these answers both helped!

Ned Murphy
Legend
January 4, 2013

You're welcome

Ned Murphy
Ned MurphyCorrect answer
Legend
January 3, 2013

Since the return of the i value is conditional it is possible the function will fail to return a value.  You should probably rearrange things so that the return happens outside of the loop, where in the case of no value matching you return a -1 or some other value that could not be related to an array index.