Results 1 to 12 of 12

Thread: Return array contents from a function

  1. #1
    Join Date
    May 2010

    Return array contents from a function

    I'm having real trouble with this, hopefully someone can help. The basic structure I have is:

    function {
    declare an array (returnArray);
    do this, do that;
    return returnArray;
    document.write('The array elements are ' + returnArray);
    The problem is that I just constantly get returnArray undefined! Please help?

  2. #2
    Join Date
    May 2010
    this is due to the scope of the variable:
    function thisHasVariable(){
      var Variable=0;
      alert(Variable); // will say 1
      return Variable;
    alert(Variable); // undefined Variable only exist within {} of the thisHasVariable function
    alert(thisHasVariable());// will say 1 because the function returns that value
    var globalVar=22; // this can be used anywhere because it's declared not within {}

  3. #3
    Join Date
    May 2010
    Thanks for the reply. So how do I return the contents of an array created within a function? This is for a college assignment and so I have to use code already defined.

    So the sturcture is:

    define an array and elements (we'll call it newArray)
    call function {
    define a new array (called returnArray)
    copy the content of newArray to returnArray
    swap some elements about
    return returnArray
    write the content of returnArray to the screen.
    The problem I have is that returnArray is always undefined. I understand that it is only valid inside the function, but then we use return to be able to access the array outside of the function.

    What is going wrong? Thanks!

  4. #4
    Join Date
    Feb 2010
    <script type="text/javascript">
    //define an array and elements (we'll call it newArray )
    var newArray = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; // im comming to getcha
    // document.write(newArray); test, this works
    function whatsInAName(arr){
    //define a new array (called returnArray)
    var returnArray = [];
    //copy the content of newArray to returnArray
    returnArray = arr.slice();
    //swap some elements about
    returnArray = returnArray.sort(function(a, b){return Math.round(Math.random())}); // swap some elements via the sort function
    return returnArray;
    document.write(whatsInAName(newArray)); //write the content of returnArray to the screen.

  5. #5
    Join Date
    May 2010
    OK, this is what I have and it works. But, I want to write the elements of returnArray to the screen. All I have done here is to copy the elements of returnArray back to unsortedArray which was declared outside the function.

    So although it's work, it's still not exactly as per spec

    function bubbleSort(arrayToSort) 	{
    var length = arrayToSort.length;
    var returnArray = new Array(length);
    for (var i = 0; i < length; i = i + 1)
    	returnArray[i] = arrayToSort[i];
    var temp;
    for (x = 0; x < length; x = x +1)
    	for (var e = 0; e < (length - 1); e = e + 1)
    		if (returnArray[e] > returnArray[e+1])
    			temp = returnArray[e+1];
    			returnArray[e+1] = returnArray[e];
    			returnArray[e] = temp;
    			finished = false;
    unsortedArray = returnArray;
    var unsortedArray = [9,7,2,10,1,4,8,6,5,3];
    document.write('Unsorted array ' + unsortedArray + '<BR>');
    document.write('Sorted array ' + unsortedArray);
    As you can see, returnArray is declared inside the function. So basically the goal is for the last line of the program to be:

    document.write('Sorted array ' + returnArray);
    Thanks for your help.

  6. #6
    Join Date
    May 2010
    I think you missed the point of a function returning a value.
    function someFunction(){
    return "Hello";
    var sayHello = someFunction();
    Here the function returns a string you can return an array and assign it to another variable or you can just write out the return value without assigning it to another variable first:

    in your case:
    document.write('Sorted array ' + bubbleSort(unsortedArray).join())
    Your assignment did not specify that the function should alter the value of newArray (see post 3) but it did specify it should return an array which it doesn't now.

    leave out the line:
    unsortedArray = returnArray;

    And replace it with .... you think about that one for 30 minutes (return something ....).

    I think it's a bad idea to have us do your homework but don't mind helping you along.
    Last edited by amsterdamharu; 05-21-2010 at 10:33 AM.

  7. #7
    Join Date
    May 2010
    So I'm still somewhat confused, but at least it's working as it should now. Bit of trial and error really.

    You're quite right in not giving me the answer, that's not what I wanted. I wouldn't have learned anything to just copy it from you.

    If you have the time (and the inclination), could you just explain why I can't just write the thing the function returns?

    what my program does now is

    document.write('Sorted array ' + bubbleSort(unsortedArray));
    What I was always doing was putting return returnArray in the function since I first made the program, but it never worked (because of fault below), so I then removed it thinking it was wrong. I don't understand why I can't just use:

    This is what confused me, looks like I can't do this?

    Thanks very much for all your help, it is appreciated!

  8. #8
    Join Date
    May 2010
    I think you got it now. The function bubbleSort returns the value of returnArray when you call it.

    The variable returnArray only exist inside the bubbleSort function, this has todo with scope. So when you ask for returnArray outside of the bubbleSort function it will be undefigned.

    Declaring a variable: var myvar=...
    Scope of the variable is between the {} of a function (not an if statement)

    Code to demonstrate:
    var i=0;
    alert("global i is now:" + i);
    function test(){
     var i=22;// declaring a variable called i within the function scope 
     alert("the other variable i within the function scope is:" + i);
     var localVar="exist only within the function";
    alert("now outside the function, i is now the global i:" + i);
    // ie never shows this alert because lovalVar is undevined
    alert("localVar does not exist here, it is undefigned:" + !!localVar);
    I like to help people learn, good to see you are here to learn.

  9. #9
    Join Date
    May 2010
    Thanks for your help so far. So another question I have is that if I had a loop counter (for example) declared inside the function, how would I make that accessible outside of the function? So that I could write the counter value to the screen after the function 'exits'.

    Not the answer please, just a helping hand

  10. #10
    Join Date
    May 2010
    you could return just the counter or if you need to return multiple values return an object:
    I will give you an example because this is quite strange in syntax if you have to look it up.
    function someFunction(){
       .... some code
       return {counter:vaueOfCounter, array:valueOfArray}
    var obj=someFunction(); // assign a variable named obj to the return value of the function
    alert(obj.counter);// value of the counter
    alert(obj.array); // value of the array
    There are 2 other solutions:
    1. use global variables (not a good one) global variables can be used anywhere in the script
    2. return an array, could be ok but you have to know the index and doesn't read so easily as the object

  11. #11
    Join Date
    May 2010
    Just sounds a whole lot easier to declare a variable outside of the function for something as simple as a counter?

    Or, use document.write() just before the loop exits to display the counter?

  12. #12
    Join Date
    May 2010
    No, scoping variables is very important. See my previous post on the variable named i. Declaring a global variable when only used in a counter or loop will confuse other functions when starting a loop. And the variable stays in memory even though you never use it.

    A script might be simple but used as an include on many pages (<script src="includeThis.js") then using global variables run the risk of overwriting other variables or your global gets overwritten.

    In your example it might not make any difference but you might as well do it right, pretend this is part of some major website. If you do it like that you will learn not to use globals casually.

    As for document.write() that could work but I am not sure if your assignment is to get the value of the counter in the script or show it to the user. document.write() will show it to the user but after the function exits it's not available in script anymore.
    Last edited by amsterdamharu; 05-22-2010 at 08:10 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.17225 seconds
  • Memory Usage 2,965KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (11)bbcode_code
  • (1)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (12)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (12)postbit
  • (12)postbit_onlinestatus
  • (12)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates